Robert Klemme
8/1/2007 9:58:00 PM
On 01.08.2007 19:34, Marcin Mielzynski wrote:
> skibud2 pisze:
>> Hey Guys,
>>
>> I want to convert an array like the following to a hash. Below is my
>> current code (I am assuming there is a better way).
>>
>> Thanks
>>
>> ["foo", "bar", "foo1", "bar1","foo2", "bar2"] convert to
>> {"foo"=>"bar", "foo1"=>"bar1","foo2"=>"bar2"}
>>
>
> given:
> a = ["foo", "bar", "foo1", "bar1","foo2", "bar2"]
>
> puts Hash[*a]
>
> or:
>
> require 'enumerator'
> h = {}
> a.each_slice(2){|k,v|h[k]=v}
> puts h
If you are using Enumerator anyway you can as well do
irb(main):001:0> a = ["foo", "bar", "foo1", "bar1","foo2", "bar2"]
=> ["foo", "bar", "foo1", "bar1", "foo2", "bar2"]
irb(main):002:0> a.to_enum(:each_slice, 2).inject({}) {|h,(k,v)| h[k]=v; h}
=> {"foo1"=>"bar1", "foo2"=>"bar2", "foo"=>"bar"}
irb(main):003:0>
Kind regards
robert