From: William James Date: 2007-05-01T05:05:05+09:00 Subject: Re: Array.which_long? ( I coded an extension for Array ) On Apr 30, 6:47 am, Robert Klemme wrote: > On 30.04.2007 12:39, Robert Dober wrote: > > > > > On 4/30/07, Robert Klemme wrote: > >> On 29.04.2007 16:11, Chris Carter wrote: > >> > On 4/29/07, Billy Hsu wrote: > >> >> Hi, I'm CFC > >> >> I'm new at here. > >> >> Nice to meet you:) > > >> > > I just coded an extension for Array. > >> >> It will return the longest element of an array. > >> >> Source: > > >> >> class Array > >> >> def which_long? > >> >> # Version 1.0 > >> >> # Coded by CFC < zusocfc @ gmail . com > > >> >> # PLEASE DO NOT REMOVE THE COMMENT OF THIS FUNCTION, THANKS A LOT. > >> >> # Usage: > >> >> # ['a', 'ab', 'abc' 1234].which_long? > >> >> # => 1234 > >> >> max, long, self_cpy = 0, "", [] > >> >> self.size.times{|i| self_cpy << self[i].to_s} > >> >> self_cpy.each{|item| (max = item.size; long = item) if item.size > > >> >> max } > >> >> long > >> >> end > >> >> end > > >> >> Usage: > >> >> puts [1, 23, '456'].which_long? > >> >> => 456 > > >> >> CFC -- > > >> > How about: > >> > class Array > >> > def longest > >> > self.map {|x| x.to_s }.sort_by {|x| x.size}[-1] > >> > end > >> > end > > >> Thank you for leaving the #inject solutions to me. :-) > > Are you kidding I posted an inject solution 19h ago ;) > > I am sorry, I did not see it. > > > 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 > > 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 def longest max = map{|s| s.size}.max select{|s| s.size == max} end