Robert Klemme
4/30/2007 11:48:00 AM
On 30.04.2007 12:39, Robert Dober wrote:
> On 4/30/07, Robert Klemme <shortcutter@googlemail.com> wrote:
>> On 29.04.2007 16:11, Chris Carter wrote:
>> > On 4/29/07, Billy Hsu <ruby.maillist@gmail.com> 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
>> irb(main):001:0> %w{a ab abc 123 34}.inject{|a,b| a.size > b.size ? a
>> : b}
>> => "123"
>> irb(main):002:0> %w{a ab abc 123 34}.inject{|a,b| a.size >= b.size ? a
>> : b}
>
> You get full credits for this anyway it is really beautiful, can you
> stop being so clever ;).
Since I overlooked your posting I can't be so clever, can I? :-)
With #inject it's really special, it took me a while to pick it up and
now I can't stop using it. IIRC I even went to the exercise to
implement all methods in Enumerable by using #inject - maybe you can
find it in the archives. :-)
Kind regards
robert