From: Robert Klemme Date: 2007-05-01T00:25:08+09:00 Subject: Re: Array.which_long? ( I coded an extension for Array ) On 30.04.2007 16:11, Robert Dober wrote: > On 4/30/07, Robert Klemme wrote: > >> I am sorry, I did not see it. > I was just kidding Robert. But I *did* overlook your posting. Honestly. :-) >> > But it was to return an array of all longest elements, I guess you can >> > maybe refine it, it seems clumsy, so I repost it just if you have some >> > time to play ;) >> > >> > def longest >> > inject([]){ |s, e| >> > if s.empty? || s.first.size < e.to_s.size then [e] >> > elsif s.first.size == e.to_s.size then s << e >> > else s >> > end >> > } >> > end > >> >> Hm, I'd probably use case here. Let's see... >> >> def longest >> inject([]) do |lg, e| >> case >> when lg.empty?, lg.first.size == e.size >> lg << e >> when lg.first.size < e.size >> [e] >> else >> lg >> end >> end >> end > better already, I am still looking for *the* solution >> >> Alternative, but with higher memory consumption >> >> 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). :-) Cheers robert