Enumerable#min
Enumerable#min
The min method returns the smallest element in an enumerable collection. It compares elements using the <=> operator (spaceship operator) to determine order.
Basic Usage
Without arguments, min returns the single smallest element:
[3, 1, 4, 1, 5, 9, 2, 6].min
# => 1
["banana", "apple", "cherry"].min
# => "apple"
Getting the N Smallest Elements
Pass an integer n to get the n smallest elements as an array:
[3, 1, 4, 1, 5, 9, 2, 6].min(3)
# => [1, 1, 2]
["banana", "apple", "cherry", "date"].min(2)
# => ["apple", "banana"]
Custom Comparison with a Block
You can provide a block to define custom comparison logic:
[-5, 3, -1, 7, -2].min { |a, b| a.abs <=> b.abs }
# => -1
["hello", "world", "ruby"].min { |a, b| a.length <=> b.length }
# => "ruby"
The block must return -1, 0, or 1 (using the spaceship operator convention).
Handling Empty Collections
min returns nil when called on an empty collection:
[].min
# => nil
[].min(2)
# => []
min vs min_by
These two methods are often confused but behave differently:
| Method | What it compares |
|---|---|
min | Compares elements by their actual value using <=> |
min_by | Compares elements by the result of the block |
[1, 2, 3].min
# => 1# min_by compares by block result
["one", "two", "three"].min_by { |s| s.length }
# => "one"
Practical Examples
Finding the Lowest Price
products = [
{ name: "Widget", price: 29.99 },
{ name: "Gadget", price: 49.99 },
{ name: "Doohickey", price: 19.99 }
]
cheapest = products.min { |a, b| a[:price] <=> b[:price] }
cheapest[:name]
# => "Doohickey"
Finding the Smallest String
words = ["elephant", "cat", "giraffe", "ant"]
shortest = words.min { |a, b| a.length <=> b.length }
# => "cat"
Getting the N Cheapest Items
products = [
{ name: "Widget", price: 29.99 },
{ name: "Gadget", price: 49.99 },
{ name: "Doohickey", price: 19.99 },
{ name: "Thingamajig", price: 39.99 }
]
products.min(2) { |a, b| a[:price] <=> b[:price] }
# => [{:name=>"Doohickey", :price=>19.99}, {:name=>"Widget", :price=>29.99}]
Working with Custom Objects
class Player
attr_reader :score
def initialize(name, score)
@name = name
@score = score
end
def <=>(other)
@score <=> other.score
end
def to_s
@name
end
end
players = [
Player.new("Alice", 95),
Player.new("Bob", 87),
Player.new("Charlie", 92)
]
players.min
# => Bob (score: 87)
Performance Notes
min uses the <=> operator to compare elements. For arrays, it performs a single pass through the collection — O(n) time complexity.
When using min with a block, the comparison logic runs multiple times during the sort. For finding a single minimum, min_by is often more efficient since it only evaluates the block once per element.
See Also
- /reference/enumerable/enumerable-first/ — get the first element
- /reference/enumerable/enumerable-select/ — filter elements by condition
- /reference/enumerable/enumerable-map/ — transform each element