Hi --
Thanks for your reply, I learned more on this thread 
But I have a question:
If I have an array contain:
ary = [1, 12, 234, "456"]
there has two elements which size is 3, but the longest method just returned
one of them.
I can't solve it 
It depends how you want to break the tie. Here's a way to do it where
a size tie is broken by string comparison, which is ASCII-based. The
nonzero? method will return -1 or 1 if the two string sizes are not
equal. If they are equal, the comparison will evaluate to zero and
nonzero? will be false -- which means the second comparison (the ASCII
one) will be executed.
I've included some tests too.
class Array
def longest
sort do |a,b|
(a.to_s.size <=> b.to_s.size).nonzero? ||
a.to_s <=> b.to_s
end[-1]
end
end
require 'test/unit'
class MaxTest < Test::Unit::TestCase
def test_all_strings
assert_equal("David", %w{ Da David Dav }.longest)
end
def test_all_numbers
assert_equal(34567, [123,12345,200,34567].longest)
end
def test_tie
assert_equal("David", %w{ David Alan Black }.longest)
end
def test_mixed
assert_equal("David", [123, "David", 456].longest)
end
def test_mixed_tie
assert_equal("David", [12345, "David", "Black", 123, 98765].longest)
end
end
David
···
On 4/29/07, Billy Hsu <ruby.maillist@gmail.com> wrote:
2007/4/29, David A. Black <dblack@wobblini.net>:
>
> 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. 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 
>
> David
>
> --
> Upcoming Rails training by Ruby Power and Light:
> Four-day Intro to Intermediate
> May 8-11, 2007
> Edison, NJ
> http://www.rubypal.com/events/05082007
>
--
Taiwan Ruby Users Group:
http://www.ruby.oss.tw/
http://www.ruby.oss.tw/phpbb
--
Upcoming Rails training by Ruby Power and Light:
Four-day Intro to Intermediate
May 8-11, 2007
Edison, NJ
http://www.rubypal.com/events/05082007