Enumerable.min_by / max_by / minmax / minmax_by
Methods that retrieve the element with the minimum or maximum value from a collection. You can specify the evaluation criterion using a block.
Syntax
# Returns the element for which the block returns the smallest value.
collection.min_by { |element| expression }
# Returns the element for which the block returns the largest value.
collection.max_by { |element| expression }
# Returns the minimum and maximum elements as an array [min, max].
collection.minmax_by { |element| expression }
# Retrieves the minimum and maximum values using natural ordering.
collection.min
collection.max
collection.minmax
Method List
| Method | Description |
|---|---|
| min_by | Returns the element for which the block returns the smallest value. |
| max_by | Returns the element for which the block returns the largest value. |
| minmax_by | Returns the minimum and maximum elements as an array [min, max]. |
| min | Returns the minimum value in the collection. You can also specify a comparison method using a block. |
| max | Returns the maximum value in the collection. You can also specify a comparison method using a block. |
| minmax | Returns the minimum and maximum values as an array [min, max]. |
Sample Code
# Get the minimum and maximum values from a numeric array.
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
puts numbers.min # 1
puts numbers.max # 9
puts numbers.minmax.inspect # [1, 9]
# Get the minimum and maximum by a specific key from an array of hashes.
products = [
{ name: "Apple", price: 150 },
{ name: "Banana", price: 80 },
{ name: "Grapes", price: 500 },
{ name: "Orange", price: 100 }
]
cheapest = products.min_by { |p| p[:price] }
puts cheapest[:name] # Banana
most_expensive = products.max_by { |p| p[:price] }
puts most_expensive[:name] # Grapes
cheapest_and_most_expensive = products.minmax_by { |p| p[:price] }
puts cheapest_and_most_expensive.map { |p| p[:name] }.inspect # ["Banana", "Grapes"]
# Compare strings by length.
words = ["cat", "elephant", "ox", "hippopotamus"]
puts words.min_by { |w| w.length } # ox
puts words.max_by { |w| w.length } # hippopotamus
Details
min_by and max_by are methods from the Enumerable module that find the element with the smallest or largest value returned by the block. They are commonly used to sort and retrieve elements from an array of hashes by a specific key.
min and max without a block compare elements using their natural ordering (numeric order for numbers, alphabetical order for strings). Calling these methods on an empty collection returns nil, so be sure to check the return value before using it. To retrieve multiple minimum or maximum values, pass an argument such as min(n) or max(n) to get the top n elements as an array.
If you find any errors or copyright issues, please contact us.