From: Daniel Martin Date: 2007-01-17T04:45:15+09:00 Subject: Re: Can anyone try to solve this problems? David Madden writes: >> 2. Write a function to find the longest string in an array of >> strings. >> > Is this from the Brian Schroder Ruby Course PDF? > > Here is my function (no doubt a better on exists): Well, okay, we've heard from folks with their fancy 1.9 ruby with max_by and that &:sym notation. However, I'm a little bit surprised that this one-liner with inject didn't pop up: def longest(a) a.inject { |x,y| x.length < y.length ? y : x } end ObQuickIRBSanityCheck: irb(main):001:0> def longest(a) irb(main):002:1> a.inject { |x,y| x.length < y.length ? y : x } irb(main):003:1> end => nil irb(main):004:0> longest(%w[a bc de fgh ijkl mnopq rstu vwxyz]) => "mnopq" foldr is your friend. -- s=%q( Daniel Martin -- martin@snowplow.org puts "s=%q(#{s})",s.map{|i|i}[1] ) puts "s=%q(#{s})",s.map{|i|i}[1]