TExcelTAD
Home › Ruby › Ruby Iterators

Ruby Iterators

An iterator is a method that runs a block of code repeatedly — once per element, or a given number of times. Iterators are the Ruby way to loop: you tell the collection what to do with each item, and it handles the counting.

The block

A block is a chunk of code between do ... end or { ... }. Values are passed into it through the parameters between pipes |...|:

ruby · try it yourself
["Oslo", "Lima", "Kyiv"].each do |city|
  puts "Visiting #{city}"
end

[1, 2, 3].each { |n| print n * 10, " " }
puts
Visiting Oslo
Visiting Lima
Visiting Kyiv
10 20 30

Convention: use { } for one-line blocks and do ... end for multi-line blocks.

times, upto, downto, step

Integers have their own iterators for counting:

ruby · try it yourself
3.times { |i| puts "Attempt #{i + 1}" }

1.upto(5) { |n| print n, " " }
puts

5.downto(1) { |n| print n, " " }
puts

0.step(20, 5) { |n| print n, " " }
puts

1.0.step(2.0, 0.25) { |x| print x, " " }
puts
Attempt 1
Attempt 2
Attempt 3
1 2 3 4 5
5 4 3 2 1
0 5 10 15 20
1.0 1.25 1.5 1.75 2.0

times starts at 0, like array indexes.

each_with_index

When you need the position as well as the item:

ruby · try it yourself
podium = ["Ana", "Ben", "Chen"]
podium.each_with_index do |name, i|
  puts "#{i + 1}. #{name}"
end

podium.each.with_index(1) { |name, place| puts "#{place}) #{name}" }
1. Ana
2. Ben
3. Chen
1) Ana
2) Ben
3) Chen

each.with_index(1) lets you choose the starting number.

Iterating over a hash

A hash yields both the key and the value:

ruby · try it yourself
stock = {apples: 12, pears: 0, plums: 7}

stock.each do |fruit, qty|
  puts "#{fruit}: #{qty}"
end

stock.each_key { |k| print k, " " }
puts
p stock.sum { |_, qty| qty }
apples: 12
pears: 0
plums: 7
apples pears plums
19

An underscore (_) is a conventional name for a block parameter you don't use.

Ranges and strings

ruby · try it yourself
("a".."e").each { |ch| print ch.upcase }
puts
(1..10).step(3) { |n| print n, " " }
puts
"tick".each_char { |c| print "[#{c}]" }
puts
ABCDE
1 4 7 10
[t][i][c][k]

Iterators that build results

each just runs the block and returns the original collection. Other iterators collect the block's results — you'll study them in depth in the Enumerable lesson, but here's a preview:

ruby · try it yourself
prices = [12, 5, 30, 8]

p prices.map { |p| p * 2 }          # transform each item
p prices.select { |p| p > 10 }      # keep matching items
p prices.reject { |p| p > 10 }      # drop matching items
p prices.find { |p| p < 10 }        # first match
p prices.sum
p prices.each_slice(2).to_a          # groups of 2
p prices.each_cons(2).map { |a, b| b - a }  # differences
[24, 10, 60, 16]
[12, 30]
[5, 8]
5
55
[[12, 5], [30, 8]]
[-7, 25, -22]

Controlling iteration

break and next work inside blocks too:

ruby · try it yourself
[3, 8, -1, 6, 9].each do |n|
  next if n.even?
  break if n.negative?
  puts "odd: #{n}"
end
odd: 3

Iterators without a block return Enumerators

If you call an iterator without a block, you get an Enumerator — an object you can chain or step through manually:

ruby · try it yourself
e = [10, 20, 30].each
p e.next
p e.next
p 3.times.to_a
p "abc".each_char.with_index.map { |c, i| c * (i + 1) }
10
20
[0, 1, 2]
["a", "bb", "ccc"]

Quick reference

Iterator Example Yields
times 3.times { |i| } 0, 1, 2
upto / downto 1.upto(3) 1, 2, 3
step 0.step(10, 5) 0, 5, 10
each arr.each { |x| } every element
each_with_index arr.each_with_index { |x, i| } element + index
each_char / each_line str.each_char characters / lines
each_slice(n) arr.each_slice(2) groups of n

Test yourself

What does 3.times { |i| print i } print?

  1. 123
  2. 012
  3. 0123
  4. 333

Which block style is conventional for multi-line blocks?

  1. { ... }
  2. do ... end
  3. begin ... end
  4. ( ... )

What do you get when calling [1, 2].each without a block?

  1. nil
  2. An error
  3. An Enumerator
  4. The array [1, 2]