Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: inject issue when turning array into hash

Tags:

ruby

a = [[1, 'a'],[2, 'b'],[3, 'c'], [4, 'd']]
a.inject({}) {|r, val| r[val[0]] = val[1]}

When I run this, I get an index error

When I change the block to

a.inject({}) {|r, val| r[val[0]] = val[1]; r}

It then works.

How is ruby handling the first inject attempt that isn't getting what I want?
Is there a better way to do this?

like image 386
MxLDevs Avatar asked May 13 '12 20:05

MxLDevs


2 Answers

a.inject({}) { |r, val| r.merge({ val[0] => val[1] }) }
like image 152
Sulabh Jain Avatar answered Oct 10 '22 12:10

Sulabh Jain


There is an easier way -

a = [[1, 'a'],[2, 'b'],[3, 'c'], [4, 'd']]
b = Hash[a] # {1=>"a", 2=>"b", 3=>"c", 4=>"d"}

The reason the first method isn't working, is because inject uses the result of the block as the r in the next iteration. For the first iteration, r is set to the argument you pass to it, which in this case is {}.

like image 36
x1a4 Avatar answered Oct 10 '22 11:10

x1a4