Hi –

On 4/29/07, Billy H. removed_email_address@domain.invalid wrote:

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