From: "Jesús Gabriel y Galán" Date: 2011-02-03T00:37:20+09:00 Subject: Re: Soliciting some help with inject method On Wed, Feb 2, 2011 at 3:56 PM, Edmond Kachale wrote: > Rubysters, > > I think I am not wrong if I can solicit some knowledge. :-) > > Can any one help modify this code? > > I have: > array = [['a', 1], ['b', 2], ['a',2], ['c',4], ['d', 5], ['b',4]] > > I want to create a hash using inject method: >>> hash = {'a' => [1, 2], 'b' => [2, 4], 'c' => [4], 'd' => [5]} > > The following code gives: {"a"=>[2], "b"=>[4], "c"=>[4], "d"=>[5]} > > hash  = array.inject({}) do |result, array| > new_hash = {} > new_hash[array.first] = [array.last] > result.merge!(new_hash)  # I have tried result.update(new_hash) but it fails > too > result > end > > Here is a console friendly version of the same: > hash  = array.inject({}){|result, array| new_hash = {}; > new_hash[array.first] = [array.last]; result.merge!(new_hash); result;} > > Thanks in advance, Yet another way without inject: irb(main):001:0> array = [['a', 1], ['b', 2], ['a',2], ['c',4], ['d', 5], ['b',4]] => [["a", 1], ["b", 2], ["a", 2], ["c", 4], ["d", 5], ["b", 4]] irb(main):002:0> result = Hash.new {|h,k| h[k] = []} => {} irb(main):003:0> array.each {|key,value| result[key] << value} => [["a", 1], ["b", 2], ["a", 2], ["c", 4], ["d", 5], ["b", 4]] irb(main):004:0> result => {"a"=>[1, 2], "b"=>[2, 4], "c"=>[4], "d"=>[5]} Jesus.