------ art_41394_7580586.1133391949798
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
Here's a construct I use quite frequently:
hsh = Hash.new{ |hh,kk| hh[kk] = Array.new }
What this does is that the default value of hsh[somekey] is a new array.
So, with that, we can do this:
a = [['a', 'b', 'c'],[1,2,2]]
hsh = Hash.new{ |hh,kk| hh[kk] = Array.new }
a[0].each_index{ |ii|
hsh[ a[1][ii] ].push( a[0][ii] )
}
hsh => {1=>["a"], 2=>["b", "c"]}
On 11/30/05, Sean O'Halpin <sean.ohalpin / gmail.com> wrote:
>
> On 11/30/05, Chris McMahon <christopher.mcmahon / gmail.com> 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]
> >
> > ?
> >
> > Thanks,
> > -Chris
> >
>
> Here's another way:
>
> a = [['A', 'B', 'C'],[1,2,3]]
> h = Hash[*a[0].zip(a[1]).flatten]
> p h
> -- OUTPUT --
> {"A"=>1, "B"=>2, "C"=>3}
>
> Regards,
>
> Sean
>
>
------ art_41394_7580586.1133391949798--