Hanfei Sun Hanfei Sun - 4 months ago 6
Ruby Question

Array to hash in ruby

Input:

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


Output:

{: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
>> Hash[*a.flatten]
=> {:a=>"apple", :b=>"bear"}

Or a prettier one:

>> Hash[a] 

Or after 2.1:

>> a.to_h