How to Use min_by and max_by in Ruby: Simple Guide
min_by and max_by are Enumerable methods that return the element for which the given block returns the smallest or largest value, respectively. You pass a block that calculates a value for each element, and min_by or max_by returns the element with the minimum or maximum of those values.Syntax
The methods min_by and max_by are called on collections like arrays. You provide a block that computes a value for each element. The method returns the element with the smallest or largest computed value.
collection.min_by { |element| expression }collection.max_by { |element| expression }
Here, collection is an Enumerable (like an array), and expression is how you measure each element.
min_element = collection.min_by { |element| expression }
max_element = collection.max_by { |element| expression }Example
This example shows how to find the shortest and longest words in an array using min_by and max_by. The block returns the length of each word, so the methods return the words with the smallest and largest lengths.
words = ["apple", "banana", "pear", "grapefruit", "kiwi"] shortest = words.min_by { |word| word.length } longest = words.max_by { |word| word.length } puts "Shortest word: #{shortest}" puts "Longest word: #{longest}"
Common Pitfalls
One common mistake is forgetting to provide a block, which causes an error because min_by and max_by need a block to know how to compare elements.
Another is using min or max when you want to compare by a specific attribute; those methods compare elements directly, not by a computed value.
numbers = [10, 5, 8] # Wrong: no block given # numbers.min_by # Wrong: compares numbers directly, not by some property # numbers.min { |a, b| a <=> b } # works but redundant # Correct: use block to compare by a property words = ["ten", "five", "eight"] shortest_word = words.min_by { |word| word.length } puts shortest_word
Quick Reference
- min_by: Returns element with smallest block value.
- max_by: Returns element with largest block value.
- Both require a block to specify the comparison key.
- Useful for finding elements by a specific attribute or calculation.
