From: dblack@... Date: 2005-12-14T05:31:33+09:00 Subject: Re: Array.invert --8323328-641301970-1134505886=:30520 Content-Type: MULTIPART/MIXED; BOUNDARY="8323328-641301970-1134505886=:30520" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --8323328-641301970-1134505886=:30520 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Wed, 14 Dec 2005, Simon Kr=C3=B6ger wrote: > Christer Nilsson wrote: >> Kroeger, Simon (ext) wrote: >>=20 >>> Hi Christer, >>>=20 >>> don't take this to serious: >>>=20 >>> a =3D [[1,3],[1,4,5]] >>> p (0...a.size).zip(a).inject([]){|s, b| b[1].each{|i| (s[i] ||=3D []) <= < >>> b[0]}; s} >>>=20 >>> =3D> [nil, [0, 1], nil, [0], [1], [1]] >>>=20 >>> cheers >>>=20 >>> Simon >>=20 >>=20 >> Ruby is so fun, it's impossible to be serious :-) >>=20 >> a.invert works but not a.invert.invert >>=20 >> Can you fix that in your amazing oneliner ? >> Clue: nil.each is the bummer. >>=20 >> Christer > > rofl! > > i will give you two: > > class Array > def invert > zip([*(0...size)]).inject([]){|s, b| (b.first || []).each{|i| (s[i] ||= =3D=20 > []) << b.last}; s} > end > end You could also do: b.first.to_a, which will be [] for nil and self if b.first is an array. David --=20 David A. Black dblack@wobblini.net "Ruby for Rails", forthcoming from Manning Publications, April 2006! --8323328-641301970-1134505886=:30520-- --8323328-641301970-1134505886=:30520--