"apple", :b=>"bear"} I think about it to do this: h = a.injec...">

Ruby hash array

Input:

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

Output:

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

I think about it to do this:

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

But I still think this is not the best way. Does anyone have any better solutions?

+4
source share
1 answer
 >> Hash[*a.flatten] => {:a=>"apple", :b=>"bear"} 

Or more beautiful:

 >> Hash[a] 

Or after 2.1:

 >> a.to_h 
+10
source

All Articles