I want to use min(5,10)
, or Math.max(4,7)
. Are there functions to this effect 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.
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.
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.
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.
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]
You can use
[5,10].min
or
[4,7].max
It's a method for Arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With