Question

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

Was it helpful?

Solution

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"

OTHER TIPS

use array map: a.map{|v|foo(v)}.max

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top