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?
a.inject({}) { |r, val| r.merge({ val[0] => val[1] }) }
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 {}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With