Hanfei Sun Hanfei Sun - 1 year ago 80
Ruby Question

Array to hash in ruby


a = [[:a, "apple"], [:b, "bear"]]


{:a=>"apple", :b=>"bear"}

I think of this way to do it:

h = a.inject({}){|dic,i| dic.merge({i[0]=>i[1]})}

But I still think it's not the best way. Does anyone have better solutions?

Answer Source
>> Hash[*a.flatten]
=> {:a=>"apple", :b=>"bear"}

Or a prettier one:

>> Hash[a] 

Or after 2.1:

>> a.to_h
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download