How to find a min/max with Ruby

I want to use min(5,10), or Math.max(4,7). Are there functions to this effect in Ruby?

6 Answers

You can do

[5, 10].min

or

[4, 7].max

They come from the Enumerable module, so anything that includes Enumerable will have those methods available.

v2.4 introduces own Array#min and Array#max, which are way faster than Enumerable's methods because they skip calling #each.

@nicholasklick mentions another option, Enumerable#minmax, but this time returning an array of [min, max].

[4, 5, 7, 10].minmax
=> [4, 10]
11

You can use

[5,10].min 

or

[4,7].max

It's a method for Arrays.

2

All those results generate garbage in a zealous attempt to handle more than two arguments. I'd be curious to see how they perform compared to good 'ol:

def max (a,b) a>b ? a : b
end

which is, by-the-way, my official answer to your question.

3

If you need to find the max/min of a hash, you can use #max_by or #min_by

people = {'joe' => 21, 'bill' => 35, 'sally' => 24}
people.min_by { |name, age| age } #=> ["joe", 21]
people.max_by { |name, age| age } #=> ["bill", 35]

In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:

def max(*values) values.max
end

Output:

max(7, 1234, 9, -78, 156)
=> 1234

This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil, since calling Enumerable#max on an empty array object returns nil.

If you want to define this method on the Math module, this should do the trick:

module Math def self.max(*values) values.max end
end

Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:). See Dave Morse's answer for a simpler and faster method.

1
def find_largest_num(nums) nums.sort[-1]
end
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like