Enumerable#min and Enumerable#max
The Enumerable#min and Enumerable#max methods are used to find the minimum and maximum elements in a collection, respectively. They can be called with or without a block. When called without a block, they return the smallest or largest element based on the natural ordering of the elements. When called with a block, they use the block's return value to compare the elements.
numbers = [5, 2, 9, 1, 5, 6]
numbers.min # => 1
numbers.max # => 9
words = %w[the quick brown fox jumps over the lazy dog]
words.min # => "brown"
words.max # => "the"
# Using a block to find the shortest and longest words
words.min { |a, b| a.length <=> b.length } # => "the"
words.max { |a, b| a.length <=> b.length } # => "quick"
const numbers = [5, 2, 9, 1, 5, 6];
const min = Math.min(...numbers); // 1
const max = Math.max(...numbers); // 9
const words = [
"the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"
];
const minWord = words.reduce((min, word) => word < min ? word : min);
// => "brown"
const maxWord = words.reduce((max, word) => word > max ? word : max);
// => "the"
// Finding the shortest and longest words using a custom comparison
words.reduce(
(shortest, word) => word.length < shortest.length ? word : shortest
);
// => "the"
words.reduce(
(longest, word) => word.length > longest.length ? word : longest
);
// => "quick"
By passing in an integer argument, we can get the smallest or largest n elements from the collection:
numbers = [5, 2, 9, 1, 5, 6]
numbers.min(3) # => [1, 2, 5]
numbers.max(3) # => [9, 6, 5]
const numbers = [5, 2, 9, 1, 5, 6];
[...numbers].sort((a, b) => a - b).slice(0, 3); // => [1, 2, 5]
[...numbers].sort((a, b) => b - a).slice(0, 3); // => [9, 6, 5]
In cases where we need both the minimum and maximum values, we can use Enumerable#minmax, which returns an array containing both the minimum and maximum elements in one go:
words = %w[the quick brown fox jumps over the lazy dog]
min, max = words.minmax
min # => "brown"
max # => "the"
const words = [
"the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"
];
const { min, max } = words.reduce(
(result, word) => {
if (word < result.min) result.min = word;
if (word > result.max) result.max = word;
return result;
},
{ min: words[0], max: words[0] }
);
min; // "brown"
max; // "the"
Minimal yet clear as day. Just the way we like it!
History
Enumerable#min and Enumerable#max have been around since Ruby's inception.
Enumerable#minmax was released in Ruby 1.8.7 in May 2008.
The integer argument variant was added in Ruby 2.2, released in December 2014.