Robert Dober
4/29/2007 3:07:00 PM
On 4/29/07, David A. Black <dblack@wobblini.net> wrote:
> Hi --
>
> On 4/29/07, Robert Dober <robert.dober@gmail.com> wrote:
> > On 4/29/07, David A. Black <dblack@wobblini.net> wrote:
> > > You're doing too much work -- let Ruby do it :-)
> > ... for sure, but
> > >
> > > class Array
> > > def longest
> > > map {|e| e.to_s }.max
> > > end
> > > end
> > I think it is not exactly what OP wanted
> > because %w{x aaaa}.max is "x"
> > so I will try to comply to his needs
> > def longest
> > map{ |e| [e.to_s.size, e.to_s]}.max.first
> > end
>
> You're right that I was wrong (because I didn't do the .size thing),
> but yours gives you an integer:
>
> ['x', 'aaaa'].longest # => 4
>
> I think you'd have to reverse your array.
Together we might get there ;), maybe just applying #last instead of #first.
See Harry's code too, which
> uses a block with max.
Which is great, I admit that is the nicest solution, learned something again :)
You could also do:
>
> sort_by {|e| e.to_s.size }[-1]
That's nice too, (personally I prefer #last to [-1])
>
> (since there's no max_by :-)
yet
>
>
Cheers
Robert
>
--
You see things; and you say Why?
But I dream things that never were; and I say Why not?
-- George Bernard Shaw