From: Gregory Brown Date: 2007-01-16T14:39:26+09:00 Subject: Re: Can anyone try to solve this problems? On 1/15/07, David Madden wrote: > >> > >> def longest(a) > >> word = '' > >> a.each do |i| > >> if word.length < i.length > >> word = i > >> end > >> end > >> word > >> end > > > > ['fodfsafdfsdfso','bar','bazzzzzz'].sort_by { |s| s.length }.pop > > > > The beauty of a one line solution :-) > > also...what is this about: > > max_by(&:length) This is an Enumerable method from 1.9 http://ruby-doc.org/core-1.9/classes/Enumerable.html It is a much better solution than what I offered, since it doesn't sort the list first. The actual method is implemented in C, but here is one way of doing it in Ruby, to help you understand what's going on (maybe :) ) >> seltzer:~ sandal$ irb >> module Enumerable >> def max_by >> m={} >> each { |e| ?> v = yield(e) >> m[:value] ||= v >> if v > m[:value] >> m[:obj] = e; m[:value] = v; ?> end >> } >> m[:obj] >> end >> end => nil >> ['foo','bartdfaggdgs','afdfd'].max_by { |e| e.length } => "bartdfaggdgs" >> class Symbol >> def to_proc >> lambda { |x| x.send(self) } >> end >> end => nil >> ['foo','bartdfaggdgs','afdfd'].max_by &:length => "bartdfaggdgs"