method
max
max(p1 = v1)
public
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"
If the n argument is given, maximum n elements are returned as an array, sorted in descending order.
a = %w[albatross dog horse] a.max(2) #=> ["horse", "dog"] a.max(2) {|a, b| a.length <=> b.length } #=> ["albatross", "horse"] [5, 1, 3, 4, 2].max(3) #=> [5, 4, 3]
Register or
log in
to add new notes.
Mange -
February 16, 2009
2 thanks
Capping values
This method is very useful when you want to cap values:
# minimum ≤ value value = [input.to_i, minimum].max # value ≤ maximum value = [input.to_i, maximum].min # minimum ≤ value ≤ maximum value = [ [input.to_i, minimum].max, maximum ].min # Practical example: Make sure destination is within container destination.x = [ [current.x + current.velocity.x, 0].max, container.width ].min destination.y = [ [current.y + current.velocity.y, 0].max, container.height ].min
MattStopa -
March 15, 2012
0 thanks