method

max

ruby latest stable - Class: Enumerable
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]

2Notes

Capping values

Mange · Feb 16, 20092 thanks

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

Video Explanation for max and min

MattStopa · Mar 14, 2012