From: Rick DeNatale Date: 2007-05-03T23:27:35+09:00 Subject: Re: Array.which_long? ( I coded an extension for Array ) On 4/29/07, James Edward Gray II wrote: > On Apr 29, 2007, at 9:38 AM, David A. Black wrote: > > I think you'd have to reverse your array. See Harry's code too, which > > uses a block with max. You could also do: > > > > sort_by {|e| e.to_s.size }[-1] > > > > (since there's no max_by :-) > > Well, not yet: > > $ ruby_yarv -e 'p %w[c bb aaa].max_by { |e| e.to_s.size }' > "aaa" Actually Array#max already takes a block, and the Rdoc actually uses almost this very use case to document it: $ qri Array#max --------------------------------------------------------- Enumerable#max enum.max => obj enum.max {|a,b| block } => obj ------------------------------------------------------------------------ Returns the object in enum with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b. a = %w(albatross dog horse) a.max #=> "horse" a.max {|a,b| a.length <=> b.length } #=> "albatross" Harry gave a solution along these lines early on in the thread, but no one seems to have noticed. The observation that 1.9 is adding max_by is interesting, but it's more a matter of syntactic sugar than the difference between sort and sort_by since max only needs to evaluate the block once for each element. Now max_by is nicer since the block just needs to return the comparison value rather than a comparison result. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/