Ross Bamford
5/12/2006 7:13:00 PM
On Fri, 12 May 2006 18:43:45 +0100, Geoff <skhisma@gmail.com> wrote:
> So I'm looking to create a Hash from a string which is pretty much
> formatted like you would create a hash:
>
> theString = "foo=>1,bar=>2,baz=>'go fish'"
>
> and i was wondering if anyone had any nice and simple ideas for how to
> grab this out. I came up with a little way to do it but i was just
> wondering if anyone out there can think of a shorter way.
>
> Here's what i came up with:
>
> login = Hash.new
> theString.split(',').each {|pair| pair.match(/(.+)=>(.+)/);
> login[$1.intern]=$2 }
>
Depends on exactly how you want the Hash, but maybe you could do:
h = Hash[*the_string.split(',').map { |e| e.split('=>') }.flatten]
# => {"baz"=>"'go fish'", "foo"=>"1", "bar"=>"2"}
or:
h = Hash[*the_string.split(',').map do |e|
e.split('=>').inject { |k,v| [k.intern,eval(v)] }
end.flatten]
# => {:foo=>1, :bar=>2, :baz=>"go fish"}
Unfortunately, if you want the second style I think you're stuck with eval
and it's (deserved) reputation as slow and insecure.
--
Ross Bamford - rosco@roscopeco.remove.co.uk