You can do this without an inject, with a simple iteration and a bit of ||=

>> a = [['a', 1], ['b', 2], ['a',2], ['c',4], ['d', 5], ['b',4]]
=> [["a", 1], ["b", 2], ["a", 2], ["c", 4], ["d", 5], ["b", 4]]
>> h = {}
=> {}
>> a.each { |k, v| h[k] ||= []; h[k] << v }
=> [["a", 1], ["b", 2], ["a", 2], ["c", 4], ["d", 5], ["b", 4]]
>> h
=> {"a"=>[1, 2], "b"=>[2, 4], "c"=>[4], "d"=>[5]}


On Wed, Feb 2, 2011 at 2: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 = [['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!!**
> *
>