Thread: Ruby Snippets
View Single Post
Old Apr 9th, 2006, 4:10 PM   #10
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
Rep Power: 4 Jessehk is on a distinguished road
This method will be available in version 1.9, but I wrote my own. I'm sure it could be done more efficiently somehow.

class Array
	def max_by(&block)
		elem, value = 0, 0

		each do |v|
			result = block.call(v)
			
			if result > value
				elem, value = v, result
			end
		end

		elem
	end
end

Example usage:

$ irb --simple-prompt
>> require 'max_by'
=> true
>> "Hello, my name is Jesse. Isn't that fantastic?".scan(/\w+/).max_by { |x| x.length }
=> "fantastic"
>>
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote