📅  最后修改于: 2023-12-03 15:41:11.702000             🧑  作者: Mango
The minmax()
function in the Enumerable module of Ruby returns an array containing the minimum and maximum value from an enumerable object. The enumerable object can be an array, hash or a range.
enumerable.minmax { |a, b| block }
Or
enumerable.minmax
enumerable
: The enumerable object for which you want to find the minimum and maximum value.
block
: A comparison block that takes two arguments a
and b
and returns -1
, 0
or 1
. This block is used to compare the values in the enumerable object. The block is optional. If absent, the minmax
function uses the default comparison operator <=>
.
The minmax()
function returns an array containing the minimum and maximum value from the enumerable object.
numbers = [3, 5, 2, 6, 1, 8]
minmax = numbers.minmax
puts "Minimum value is #{minmax[0]}"
puts "Maximum value is #{minmax[1]}"
Output:
Minimum value is 1
Maximum value is 8
prices = {'apple' => 0.5, 'banana' => 0.3, 'pear' => 0.8}
minmax = prices.minmax { |a, b| a[1] <=> b[1] }
puts "Minimum value is #{minmax[0]}"
puts "Maximum value is #{minmax[1]}"
Output:
Minimum value is ["banana", 0.3]
Maximum value is ["pear", 0.8]
In the above example, we are comparing the values of the hash to get the minimum and maximum price.
The minmax()
function in Ruby returns the minimum and maximum value from an enumerable object. It is a handy function to have when you need to find the boundary values in a collection.