Ruby Enumerable
Enumerable is a module (a bundle of methods) shared by arrays, hashes, ranges, sets and any class that defines each. It contains the collection methods Ruby is famous for: map, select, reduce, group_by, sort_by, each_with_object and many more. Mastering them replaces most hand-written loops.
All examples in this lesson use the same small data set:
orders = [
{id: 1, customer: "Ana", total: 42.0, status: :paid},
{id: 2, customer: "Ben", total: 15.5, status: :pending},
{id: 3, customer: "Ana", total: 99.9, status: :paid},
{id: 4, customer: "Cleo", total: 8.0, status: :cancelled},
{id: 5, customer: "Ben", total: 61.0, status: :paid},
]
paid = orders.select { |o| o[:status] == :paid }
p paid.map { |o| o[:id] }
p paid.sum { |o| o[:total] }
p orders.map { |o| o[:customer] }.uniq[1, 3, 5]
202.9
["Ana", "Ben", "Cleo"]
Transform: map, flat_map, filter_map
| Method | Returns |
|---|---|
map |
a new array with the block's result for each element |
flat_map |
like map, then flattens one level |
filter_map |
map, keeping only truthy results |
p [1, 2, 3].map { |n| n * n }
p ["a b", "c"].flat_map(&:split)
p [5, 12, 7, 20].filter_map { |n| n * 10 if n > 6 }[1, 4, 9]
["a", "b", "c"]
[120, 70, 200]
Filter: select, reject, find, partition
nums = [3, 8, 15, 4, 23, 42]
p nums.select(&:even?) # alias: filter
p nums.reject(&:even?)
p nums.find { |n| n > 10 } # alias: detect
p nums.partition { |n| n < 10 }
p nums.take_while { |n| n < 15 }
p nums.grep(10..30)[8, 4, 42]
[3, 15, 23]
15
[[3, 8, 4], [15, 23, 42]]
[3, 8]
[15, 23]
grep filters with ===, so it accepts ranges, classes and regexes.
Aggregate: reduce, sum, count, min_by, max_by
words = %w[pear banana fig cherry]
p words.reduce(0) { |total, w| total + w.length }
p words.sum(&:length)
p words.count { |w| w.length > 3 }
p words.min_by(&:length)
p words.max_by(&:length)
p words.minmax_by(&:length)
p (1..5).inject(:*)19
19
3
"fig"
"banana"
["fig", "banana"]
120
reduce (alias inject) starts with an accumulator (here 0) and feeds each element into the block together with the running result.
Build a structure: each_with_object, to_h, tally
each_with_object threads one object (often a hash) through the iteration and returns it at the end — clearer than reduce for building collections:
orders = [
{customer: "Ana", total: 42.0},
{customer: "Ben", total: 15.5},
{customer: "Ana", total: 99.9},
]
spent = orders.each_with_object(Hash.new(0)) do |o, acc|
acc[o[:customer]] += o[:total]
end
p spent
p orders.to_h { |o| [o[:total], o[:customer]] }
p orders.map { |o| o[:customer] }.tally{"Ana" => 141.9, "Ben" => 15.5}
{42.0 => "Ana", 15.5 => "Ben", 99.9 => "Ana"}
{"Ana" => 2, "Ben" => 1}
Group and sort: group_by, sort_by, chunk_while
people = [["Lea", 34], ["Max", 19], ["Ida", 34], ["Tom", 27], ["Zoe", 19]]
by_age = people.group_by { |_, age| age }
p by_age.transform_values { |list| list.map(&:first) }
p people.sort_by { |name, age| [-age, name] }.map(&:first)
p [1, 2, 3, 7, 8, 12].chunk_while { |a, b| b == a + 1 }.to_a{34 => ["Lea", "Ida"], 19 => ["Max", "Zoe"], 27 => ["Tom"]}
["Ida", "Lea", "Tom", "Max", "Zoe"]
[[1, 2, 3], [7, 8], [12]]
Sorting by an array [-age, name] sorts by age descending, then by name.
Pairs and windows: zip, each_slice, each_cons
names = %w[Ann Bob Cy]
scores = [88, 92, 75]
p names.zip(scores).to_h
p (1..7).each_slice(3).to_a
p [10, 13, 19, 20].each_cons(2).map { |a, b| b - a }
p names.each_with_index.to_a{"Ann" => 88, "Bob" => 92, "Cy" => 75}
[[1, 2, 3], [4, 5, 6], [7]]
[3, 6, 1]
[["Ann", 0], ["Bob", 1], ["Cy", 2]]
Questions: any?, all?, none?, one?, include?
temps = [21, 25, 30, 19]
p temps.any? { |t| t > 28 }
p temps.all?(15..35)
p temps.none?(&:negative?)
p temps.one? { |t| t < 20 }
p temps.include?(25)true
true
true
true
true
Lazy enumeration
lazy processes elements one at a time, only as far as needed. It even works on infinite ranges:
first_squares = (1..).lazy.map { |n| n * n }.select(&:even?).first(4)
p first_squares[4, 16, 36, 64]
Putting it together
sales = [
{region: "north", product: "tea", qty: 4, price: 3.5},
{region: "south", product: "coffee", qty: 2, price: 4.0},
{region: "north", product: "coffee", qty: 5, price: 4.0},
{region: "south", product: "tea", qty: 7, price: 3.5},
]
report = sales
.group_by { |s| s[:region] }
.transform_values { |rows| rows.sum { |r| r[:qty] * r[:price] } }
.sort_by { |_, revenue| -revenue }
report.each { |region, revenue| puts "#{region.ljust(6)} #{format('%.2f', revenue)}" }north 34.00
south 32.50
Tip: Read a chain from top to bottom like a recipe: group the rows, sum each group, sort the result. If a chain gets longer than ~5 steps, give intermediate results names.
Test yourself
What does [1, 2, 3, 4].each_with_object([]) { |n, acc| acc << n if n.odd? } return?
- [1, 2, 3, 4]
- [1, 3]
- nil
- [2, 4]
Which method splits a collection into a hash of arrays by a key?
partitiongroup_bytallychunk
What does %w[aa b ccc].max_by(&:length) return?
- "aa"
- "b"
- "ccc"
- 3