From: Andrew Wagner Date: 2011-02-03T00:17:47+09:00 Subject: Re: Soliciting some help with inject method --0016e6d7e355436081049b4e17eb Content-Type: text/plain; charset=UTF-8 Here's one simple way to do it: hash = array.inject({}) do |result, array| key,val = array if result[key].nil? result[key] = [val] else result[key].push val end result end On Wed, Feb 2, 2011 at 9:56 AM, Edmond Kachale < edmond.kachale@baobabhealth.org> 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, > > --- > Edmond > Software Developer | Baobab Health Trust (http://www.baobabhealth.org/) | > Malawi > > Cell: +265 999 465 137 | +265 881 234 717 > > *I wish you a Merry Christmas and a Prosperous New Year 2011!!** > * > --0016e6d7e355436081049b4e17eb--