Explain it simply
Explain it simply
An iterator is a method that walks through a collection for you. You hand it a small piece of code, called a block, and it runs that block once for every item. Instead of managing an index and a counter yourself, you describe what should happen to each item: print it with each, transform it with map, keep some items with select, or boil everything down to one value with reduce.
Picture a conveyor belt in a factory. The belt, which is the iterator, brings every item to your station, and the block is whatever you do at that station. The belt knows when the items run out, so you never write a stopping condition.
Problem → Why → Solution
The problem: index loops invite bugs
Imagine you need the tax-included price of every item in a list. With the loops you just learned, you create an empty result array, an index variable and a bound to compare against, and then remember to add 1 on every pass. The loop below does that, but it uses <= instead of <, so the last pass reads prices[3] on a three-item array. That position holds nil, and nil * 1.1 raises an error.
prices = [100, 250, 400]
taxed = []
i = 0
while i <= prices.length # off by one: valid indexes are 0..2
taxed << prices[i] * 1.1 # NoMethodError: undefined method '*' for nil
i += 1
endWhy an iterator is safer
An index loop makes you juggle three things at once: the counter, the bound and the result array. Each one is a place for a bug, and none of the code says what you actually want. An iterator hides the counter and the bound inside the method, so there is nowhere for that bug to live, and the method name (each, map, select) states your intent.
Core concept: the method walks, the block decides
In Ruby an iterator is an ordinary method that accepts a block and calls it with yield. A block is the code between do ... end or { ... }, and its parameters sit between pipes, as in |price|. By convention you use braces for one-liners and do ... end when the block spans several lines. The method decides how to walk and the block decides what to do, so one each can print, add up or build strings, and arrays, hashes and ranges can all offer the same each.
The first distinction to learn is each versus map. each is for side effects such as printing, saving or sending, and it returns the receiver itself, so its return value is rarely useful. map is for transformation: it returns a brand-new array holding the block's results and leaves the original untouched. If you push into an empty array inside each, you are rebuilding map by hand; if you call map and throw the result away, you have misused it.
Next comes the filtering and folding family. select (also called filter) keeps the items for which the block returns something truthy, and reject keeps the others. find returns the first match or nil. reduce (also called inject) folds a collection into one value by carrying an accumulator, so reduce(0) { |sum, x| sum + x } starts at 0 and adds every item. For common jobs, dedicated methods read better: sum, count, min, max, any?, all? and none?. By convention a method ending in ? answers true or false, and one ending in ! changes the receiver in place, as map! does.
A hash hands the block a key and a value (hash.each { |name, price| ... }), and each_with_index hands over the item and its position. Most iterators called without a block return an Enumerator instead of running, which is why chains such as each_with_index.map and map.with_index work. And &:name is shorthand for passing a method by name: names.map(&:upcase) means names.map { |n| n.upcase }.
- Iterator picks the next item
- Hands the item to your block
- Block returns its last expression
- Iterator keeps or ignores the result
each ignores the block's result, map collects it, select checks whether it is truthy, and reduce carries it into the next pass.
General pattern
collection.each { |item| action }
collection.map { |item| new_value }
collection.select { |item| test }
collection.reduce(start) { |acc, item| next_acc }
collection.each do |item|
action
endAfter the method call you write a block as { |parameter| ... } or do |parameter| ... end. The last expression of the block is its result: map collects it as the new value and select treats it as the test. With reduce the block takes two parameters, the accumulator and the item, and returns the next accumulator.
Example: print, transform, filter and total a price list
Four iterators work on one array in turn. each prints lines, map calculates the tax-included prices, select picks the cheap ones, and reduce produces the total.
Watch the last line. map and select return new arrays, so prices itself is unchanged. That is one reason iterators are safe to chain.
prices = [100, 250, 400]
prices.each do |price|
puts "Price: #{price} yen"
end
with_tax = prices.map { |price| (price * 1.1).round }
p with_tax
cheap = prices.select { |price| price < 300 }
p cheap
total = prices.reduce(0) { |sum, price| sum + price }
puts "Total: #{total} yen"
puts "Prices still: #{prices}"Code breakdown
- each
prices.each do |price|The block runs three times and price becomes 100, 250 and 400 in turn. each itself returns the prices array, so there is nothing to save.
- map
(price * 1.1).roundThe block's last expression becomes the new item. Multiplying by 1.1 yields floats such as 110.00000000000001, so round is called to get the clean integers [110, 275, 440].
- select
prices.select { |price| price < 300 }Only the items for which the block returns true stay, so 100 and 250 remain and 400 is dropped. The result is a new array.
- reduce
prices.reduce(0) { |sum, price| sum + price }sum starts at 0. On every pass the block returns sum + price and that becomes the next sum, so it grows 0, 100, 350, 750 and total ends as 750.
- unchanged
puts "Prices still: #{prices}"None of map, select or reduce changed prices, so it still prints [100, 250, 400]. Only the bang methods such as map! change an array in place, and you should use them deliberately.
Price: 100 yen
Price: 250 yen
Price: 400 yen
[110, 275, 440]
[100, 250]
Total: 750 yen
Prices still: [100, 250, 400]Choosing the right iterator
| Method | Use it when | Returns |
|---|---|---|
| each | You want a side effect for every item | The receiver itself |
| map | You want a new value for every item | A new array |
| select / reject | You want to keep or drop items by a test | A new array |
| find | You want the first item that passes a test | The item, or nil |
| reduce | You want to fold everything into one value | Whatever the accumulator ends as |
| each_with_object | You build a hash or array while walking | The object you passed in |
| each_slice(n) / each_cons(n) | You need batches, or sliding windows, of n items | An Enumerator when called without a block |
The code below shows six more everyday iterators on one names array. each_slice(2) gives batches of two, and each_cons(2) gives overlapping neighbour pairs, which is why bo appears in two pairs. Ruby 4.0.9 prints the hash result as {"ann" => 3, ...} with spaces around the arrow; versions before Ruby 3.4 printed {"ann"=>3, ...}.
names = %w[ann bo cy dee]
names.each_with_index { |name, i| puts "#{i + 1}. #{name}" }
p names.map(&:upcase) # ["ANN", "BO", "CY", "DEE"]
p names.each_slice(2).to_a # [["ann", "bo"], ["cy", "dee"]]
p names.each_cons(2).to_a # [["ann", "bo"], ["bo", "cy"], ["cy", "dee"]]
p names.each_with_object({}) { |name, lengths| lengths[name] = name.length }
p names.map.with_index(1) { |name, i| "#{i}:#{name}" } # ["1:ann", "2:bo", ...]Peeking inside: a map written with yield
Iterators are not magic; they are ordinary methods that use yield. When you write yield item, Ruby runs the block the caller supplied with that item and hands the block's last expression back as the value of yield. The my_map below shows this, and it is exactly why the built-in map can collect the block's results. The Blocks & Yield lesson goes deeper into this.
def my_map(items)
result = []
items.each { |item| result << yield(item) }
result
end
p my_map([1, 2, 3]) { |n| n * n } # [1, 4, 9]Changing a collection while you walk it
Deleting items from an array inside its own each shifts the later items one slot to the left, and the loop then steps over a neighbour. In the [2, 4, 6, 1] example below, deleting 2 moves 4 into index 0, but the loop continues at index 1, which now holds 6, so 4 survives the cleanup. The safe options are to build a new array with reject, or to use a purpose-built method such as delete_if. A hash is stricter: adding a new key while iterating it makes Ruby raise a RuntimeError.
nums = [2, 4, 6, 1]
nums.each { |n| nums.delete(n) if n.even? }
p nums # [4, 1] (4 was skipped)
nums = [2, 4, 6, 1]
p nums.reject(&:even?) # [1] a new array
nums.delete_if(&:even?) # or let delete_if do the removal safely
p nums # [1]
scores = { ann: 1 }
begin
scores.each { |name, _| scores[:bo] = 2 }
rescue => e
puts "#{e.class}: #{e.message}" # RuntimeError: can't add a new key into hash ...
endIn real projects
Where this shows up in real projects
Data work in Ruby is mostly iterator chains. A report reads records, keeps the active ones with select, turns them into display strings with map and totals a column with sum. In a Rails app users.select(&:active?).map(&:email) is everyday code, and each_slice(100) is the standard way to send records to an API in batches so that no single request grows too large. each_cons(2) gives pairs of neighbours, which is exactly what you need for day-over-day differences or a moving average.
Chains read like sentences, but every step builds an intermediate array, which matters when the data is large. For big files or endless streams, switch to the lazy enumerators you will meet in the next lesson, or to a single each_with_object pass. Also keep map blocks free of side effects: when one block both returns a value and prints or saves, the next reader cannot tell which of the two you meant.
Common mistakes
Common mistakes
1. Using each when you need a result
each returns the array it was called on, not the block's results. names.each { |n| n.upcase } therefore gives back the same lowercase names, and the upper-cased strings are thrown away. When you want the transformed values, use map and assign the result. The reverse also happens: calling map only to print builds an array nobody reads, so use each for side effects.
2. Deleting while iterating
Removing items from an array inside its own each shifts the later items one slot to the left, and the loop then steps over a neighbour. With [2, 4, 6, 1] and nums.delete(n) if n.even?, the result is [4, 1] and 4 survives. Build a new array with reject, or use delete_if, instead. Adding a new key to a hash while iterating it raises RuntimeError: can't add a new key into hash during iteration.
3. Trusting float arithmetic for money
price * 1.1 gives 110.00000000000001 for 100 and 440.00000000000006 for 400, because most decimals cannot be stored exactly in binary floating point. Print those and learners think something is broken. Round to a whole unit, as in (price * 1.1).round, or keep money in integers (cents, yen) and use BigDecimal when exact decimals matter.
4. Calling reduce without a start value on an empty array
[].reduce(:+) returns nil, so code that later calls a method on the total fails far away from the cause. Give reduce a start value, as in reduce(0, :+), or use sum, which returns 0 for an empty array.
Best practices
Best practices
- Name the block parameter after what an item is (price, user, line) instead of x once the block is longer than one line.
- Use map and select for values and each for side effects, and do not mix the two in one block.
- Prefer sum, count, min_by and friends over a hand-written reduce when one of them fits.
- Never add or remove items while iterating the same collection; iterate a copy or build a new one.
Mini challenge
Mini challenge: a shop receipt
A stationery shop keeps its items in an array of hashes. Print a receipt using iterators only; do not manage an index variable yourself.
- Print numbered lines with each_with_index, such as "1. Notebook x2 = 600 yen" (price * qty)
- Print "Total: ... yen" using sum with a block
- Chain select, map and join to print the names of items that cost more than 100 yen each
- Use each_slice(2) to print one "Page N: ..." line for every pair of items
items = [
{ name: "Notebook", price: 300, qty: 2 },
{ name: "Pen", price: 50, qty: 10 },
{ name: "Ruler", price: 120, qty: 1 },
{ name: "Eraser", price: 40, qty: 3 },
]
# TODO: numbered receipt lines with each_with_index
# TODO: the grand total, using sum with a block
# TODO: names of items above 100 yen each, using select, map and join
# TODO: one "Page N: ..." line per pair of items, using each_slice(2)Expected: 1. Notebook x2 = 600 yen 2. Pen x10 = 500 yen 3. Ruler x1 = 120 yen 4. Eraser x3 = 120 yen Total: 1340 yen Over 100 yen each: Notebook, Ruler Page 1: Notebook, Pen Page 2: Ruler, Eraser
Show hint
each_slice(2).with_index(1) with a block gives you both the page (two items) and its number. Join the names in a page with page.map { |item| item[:name] }.join(', ').
Show solution
items = [
{ name: "Notebook", price: 300, qty: 2 },
{ name: "Pen", price: 50, qty: 10 },
{ name: "Ruler", price: 120, qty: 1 },
{ name: "Eraser", price: 40, qty: 3 },
]
items.each_with_index do |item, index|
line_total = item[:price] * item[:qty]
puts "#{index + 1}. #{item[:name]} x#{item[:qty]} = #{line_total} yen"
end
total = items.sum { |item| item[:price] * item[:qty] }
puts "Total: #{total} yen"
pricey = items.select { |item| item[:price] > 100 }.map { |item| item[:name] }
puts "Over 100 yen each: #{pricey.join(', ')}"
items.each_slice(2).with_index(1) do |page, number|
puts "Page #{number}: #{page.map { |item| item[:name] }.join(', ')}"
endQuick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An iterator calls your block once per item and the block's last expression is the result; the method decides how to walk, the block decides what to do.
- each is for side effects and returns the receiver, map returns a new array and leaves the original alone, and select, reject, find, reduce and sum filter and fold.
- each_with_index, each_with_object, each_slice, each_cons and map(&:method) cover index, batch and window needs without an index variable.
- Do not change a collection while walking it: arrays skip items and hashes raise a RuntimeError when you add a key, so use reject or build a new array.
Official Ruby Documentation — Ruby Documentation