Reputation: 45941
Consider some function foo
:
def foo(input)
input * 2
end
How to get the max value of input for some array a
?
a = [3, 5, 7, 9, 6]
Something like the following (which doesn't work) should return 9:
a.max do |value|
foo(value)
end
How to do it?
Ruby 1.9.2
Upvotes: 0
Views: 303
Reputation: 81570
You need max_by
, not max
. http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-max_by
max
:
Returns the object in enum with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.
a = %w(albatross dog horse)
a.max #=> "horse"
a.max {|a,b| a.length <=> b.length } #=> "albatross"
So max
does take a block, but it doesn't do what you expected it to.
max_by
:
Returns the object in enum that gives the maximum value from the given block.
If no block is given, an enumerator is returned instead.
a = %w(albatross dog horse)
a.max_by {|x| x.length } #=> "albatross"
Upvotes: 7