From: Robert Dober Date: 2007-05-01T16:26:10+09:00 Subject: Re: Array.which_long? ( I coded an extension for Array ) On 5/1/07, Robert Klemme wrote: > On 01.05.2007 00:03, Robert Dober wrote: > > On 4/30/07, Robert Klemme wrote: > > > >> >> > >> >> def longest > >> >> lg = Hash.new {|h,k| h[k] = []} > >> >> each {|x| lg[x.size] << x} > >> >> lg.sort_by {|k,v| k}.last.pop > >> >> end > >> > good idea but I wanted inject :) > >> >> > >> > >> That's an easy transformation (left as exercise for the reader, bonus > >> points for a one liner). :-) > > > > inject( Hash.new{ |h,k| h[k]=[]} ){|h,e| h[e.size] << e}.sort_by.... > ^^^^ > The return from the block is missing. :-) Yeah I did not like this so I did not test it, I forgot the return of the block in the solution below too, but I liked the solution and therefore tested it.... > > > as this is not readable anymore let me golf a little bit > > > > inject([]){|a,e| a[e.size] = (a[e.size]||[])+[e];a}.last > > hmm that is not too bad ;) > > Couldn't you just use ||= here? > > inject([]){|a,e|(a[e.size]||=[])< > I like your idea to use the length as array index - that way no sorting > is needed. Brilliant! Well that is grossly exaggerated, but thank you anyway, the idea was yours of course I just used an Array instead of a Hash, that must be my tiny Lua background. Cheers Robert -- You see things; and you say Why? But I dream things that never were; and I say Why not? -- George Bernard Shaw