Bird
Raised Fist0
RubyHow-ToBeginner · 3 min read

How to Use min_by and max_by in Ruby: Simple Guide

In Ruby, 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.

ruby
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.

ruby
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}"
Output
Shortest word: pear Longest word: grapefruit
⚠️

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.

ruby
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
Output
five
📊

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.
✅

Key Takeaways

Use min_by and max_by to find elements with minimum or maximum values based on a block.
Always provide a block that returns the value to compare for each element.
min_by returns the element with the smallest computed value; max_by returns the largest.
Do not confuse min_by/max_by with min/max which compare elements directly.
These methods work on any Enumerable like arrays, hashes, or ranges.