Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 261
obuzek Avatar asked Aug 31 '09 20:08

obuzek


People also ask

How do you find the max value in Ruby?

The array. max() method in Ruby enables us to find the maximum value among elements of an array. It returns the element with the maximum value.

What is MAX () and MIN ()?

Python's built-in min() and max() functions come in handy when you need to find the smallest and largest values in an iterable or in a series of regular arguments.

What is .MIN in Ruby?

The min() of enumerable is an inbuilt method in Ruby returns the minimum elements or an array containing the minimum N elements in the enumerable.

What is slice in Ruby?

slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.


2 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] 
like image 124
theIV Avatar answered Sep 19 '22 15:09

theIV


You can use

[5,10].min  

or

[4,7].max 

It's a method for Arrays.

like image 39
Diego Dias Avatar answered Sep 22 '22 15:09

Diego Dias