On Wed, Feb 2, 2011 at 3:56 PM, 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 =3D [['a', 1], ['b', 2], ['a',2], ['c',4], ['d', 5], ['b',4]]
>
> I want to create a hash using inject method:
>>> hash =3D {'a' =3D> [1, 2], 'b' =3D> [2, 4], 'c' =3D> [4], 'd' =3D> [5]}
>
> The following code gives: {"a"=3D>[2], "b"=3D>[4], "c"=3D>[4], "d"=3D>[5]=
}
>
> hash =A0=3D array.inject({}) do |result, array|
> new_hash =3D {}
> new_hash[array.first] =3D [array.last]
> result.merge!(new_hash) =A0# I have tried result.update(new_hash) but it =
fails
> too
> result
> end
>
> Here is a console friendly version of the same:
> hash =A0=3D array.inject({}){|result, array| new_hash =3D {};
> new_hash[array.first] =3D [array.last]; result.merge!(new_hash); result;}
>
> Thanks in advance,

Yet another way without inject:

irb(main):001:0> array =3D [['a', 1], ['b', 2], ['a',2], ['c',4], ['d',
5], ['b',4]]
=3D> [["a", 1], ["b", 2], ["a", 2], ["c", 4], ["d", 5], ["b", 4]]
irb(main):002:0> result =3D Hash.new {|h,k| h[k] =3D []}
=3D> {}
irb(main):003:0> array.each {|key,value| result[key] << value}
=3D> [["a", 1], ["b", 2], ["a", 2], ["c", 4], ["d", 5], ["b", 4]]
irb(main):004:0> result
=3D> {"a"=3D>[1, 2], "b"=3D>[2, 4], "c"=3D>[4], "d"=3D>[5]}

Jesus.