From: Billy Hsu Date: 2007-04-29T23:53:23+09:00 Subject: Re: Array.which_long? ( I coded an extension for Array ) ------=_Part_2474_31232450.1177858400970 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Thanks for your reply, I learned more on this thread :P 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 :( thank you, Chris, David, Harry and Robert :D CFC -- 2007/4/29, David A. Black : > > Hi -- > > On 4/29/07, Robert Dober wrote: > > On 4/29/07, David A. Black 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 ------=_Part_2474_31232450.1177858400970--