Enumerable#group_by
Returns:
Hash · Updated March 13, 2026 · Enumerable ruby enumerable
The group_by method organizes collection elements into groups based on a block evaluation. It returns a hash where keys represent each unique group and values are arrays containing the elements belonging to that group.
Basic Usage
numbers = [1, 2, 3, 4, 5, 6]
grouped = numbers.group_by { |n| n.even? }
# => {false=>[1, 3, 5], true=>[2, 4, 6]}
Grouping by String Length
words = ["apple", "cat", "banana", "dog", "cherry"]
by_length = words.group_by { |word| word.length }
# => {5=>["apple"], 3=>["cat", "dog"], 6=>["banana", "cherry"]}
Grouping Strings by First Letter
names = ["Alice", "Bob", "Anna", "Bill"]
by_letter = names.group_by { |name| name[0] }
# => {"A"=>["Alice", "Anna"], "B"=>["Bob", "Bill"]}
With Nested Data
products = [
{ name: "Widget", price: 10 },
{ name: "Gadget", price: 25 },
{ name: "Gizmo", price: 10 }
]
by_price = products.group_by { |p| p[:price] }
# => {10=>[{name: "Widget", price: 10}, {name: "Gizmo", price: 10}],
# 25=>[{name: "Gadget", price: 25}]}
Practical Example: Categorizing Test Results
scores = [85, 92, 78, 90, 55, 88]
grades = scores.group_by { |s|
case
when s >= 90 then "A"
when s >= 80 then "B"
when s >= 70 then "C"
when s >= 60 then "D"
else "F"
end
}
# => {"B"=>[85, 88], "C"=>[78], "A"=>[92, 90], "F"=>[55]}
Return Value
group_by always returns a hash. Empty collections return an empty hash:
[].group_by { |x| x }
# => {}
See Also
Array#tally— counts element occurrencesArray#group_by— maps to groups (via map pattern)Hash#each— iterate over key-value pairs