Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array to hash in ruby

Tags:

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?

like image 738
Hanfei Sun Avatar asked Dec 26 '22 13:12

Hanfei Sun


1 Answers

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

Or a prettier one:

>> Hash[a] 

Or after 2.1:

>> a.to_h
like image 193
halfelf Avatar answered Jan 11 '23 08:01

halfelf