Hanfei Sun
Hanfei Sun

Reputation: 47051

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?

Upvotes: 4

Views: 495

Answers (1)

halfelf
halfelf

Reputation: 10097

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

Or a prettier one:

>> Hash[a] 

Or after 2.1:

>> a.to_h

Upvotes: 10

Related Questions