1 Dec 2005 01:03
Re: Help constructing interesting hash?
David A. Black <dblack <at> wobblini.net>
2005-12-01 00:03:21 GMT
2005-12-01 00:03:21 GMT
Hi --
On Thu, 1 Dec 2005, Chris McMahon wrote:
> Suppose I have an array of arrays like
>
> [[A, B, C][1,2,3]]
>
> I can easily make a hash (using each_with_index) where one value is
> the lookup value for the other value:
>
> 1=>A
> 2=>B
> 3=>C
>
> Now suppose I have a AoA like
>
> [[A, B, C,][1,2,2]]
>
> Is there a readable way to construct a hash like
>
> 1=>[A]
> 2=>[B, C]
Here's an inject-based way:
a.zip(b).inject({}) do |hash,(key,value)|
(hash[value] ||= []) << key
hash
end
(Continue reading)
RSS Feed