Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 134 ยท Control Flow

Iterators and Blocks Basics

Learn the Ruby way to loop - each, times, upto, downto, step, each_with_index, each_char and friends, how blocks work, block parameters, and the implicit it parameter.

In many languages you loop with a counter: start at zero, test, increment. Ruby turns this around. Instead of managing an index yourself, you hand a block of code to a collection or a number and say "run this for each item". The method that does the repeating is called an iterator. It is the idiomatic Ruby way to loop, and once it clicks you will rarely write a while loop for ordinary repetition.

This lesson introduces the most common iterators (each, times, upto, downto, step, each_with_index), explains what a block is and how block parameters work, covers the modern it shortcut, and shows how break, next and the return value behave. Writing your own iterators with yield comes later, in Blocks.

What is a block?

A block is a chunk of code attached to a method call. You write it between do ... end or between curly braces { ... }, and its parameters go between vertical bars. The method can call the block as often as it likes.

Ruby Your first iterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

each takes every element in turn, assigns it to the block parameter fruit, and runs the block. The two forms are equivalent. The convention is { } for short one-line blocks and do ... end for multi-line ones.

The braces bind more tightly than do ... end. In puts [1, 2].map { |x| x * 2 } the block goes to map, but in puts [1, 2].map do |x| x * 2 end it goes to puts, which ignores it. When in doubt, use braces for blocks whose result you use.

times, upto, downto and step

Numbers are objects with iterator methods, so counting loops need no while.

Ruby Counting iterators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

times counts from zero, which matches array indexes. upto and downto include both ends. step takes a limit and a step size (negative to go down), or the keyword form by: and to:. Floats work too, but the usual floating-point rounding applies, so compare them with care.

Iterating over collections

Arrays: each and each_with_index

When you need the position as well as the item, use each_with_index. The block receives two parameters.

Ruby Index and value together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

each.with_index(1) is a very handy idiom: calling each without a block returns an enumerator, and with_index(1) adds a counter starting at 1. See Enumerators and Lazy Enumerators for how that works.

Hashes: each with key and value

A hash yields [key, value] pairs. Destructure them with two block parameters.

Ruby Iterating a hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice the parentheses in |(name, price), i|. The enumerator passes the pair and the index; the parentheses destructure the pair. Hashes keep insertion order, so the output is predictable.

Ranges, strings and more

Almost every collection-like object has an each of some kind.

Ruby Other things you can iterate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

each_slice(n) cuts into chunks, each_cons(n) gives a sliding window. More of these live in Array Algorithms.

Block parameters

Block parameters follow looser rules than method parameters.

  • A block with fewer parameters than the values passed ignores the rest.
  • A block with more parameters gets nil for the missing ones.
  • A single array argument is automatically spread over several parameters.
Ruby How block parameters behave

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Variables introduced inside a block are local to the block and disappear after it. A variable that already exists outside the block is shared, which is how a block can accumulate a result.

Ruby Block scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The ; x syntax declares a block-local variable that shadows the outer x. You rarely need it, but it prevents accidental overwrites.

The implicit parameters: it and _1

When a block has a single, obvious parameter, Ruby 3.4 and later lets you skip naming it: it refers to the first argument. Older numbered parameters _1, _2 still exist for more than one.

Ruby it and numbered parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Use it for short, one-expression blocks. When the block is longer, or has nested blocks, a descriptive name reads better. The classic shortcut &:name, for example words.map(&:upcase), calls a method on each element and is covered in Symbols.

break, next and return values

Inside a block, next ends this pass only (like continue elsewhere) and break stops the whole iteration. Both can carry a value.

Ruby Controlling iteration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

each always returns the original collection, which is why you do not collect results with it. When you want a new array use map; when you want a total use sum or reduce; both are in Iterating and Transforming Arrays.

A common mistake is building a result array inside each with <<. It works, but map, select and sum say what you mean and are shorter.

Errors inside iterators

An exception inside the block travels out through the iterator like any other. This shows a typical bug: calling a method on nil.

Ruby NoMethodError in a block (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first name prints as Ada, then Ruby stops with main.rb:4:in 'block in <main>': undefined method 'capitalize' for nil (NoMethodError). The fix is to deal with nil before the call, with compact, with &. (see Ternary, Safe Navigation and Short-Circuit) or with a guard such as next if name.nil?.

Why prefer iterators over while?

  • No off-by-one errors. There is no counter to start or increment wrongly.
  • Intent is visible. orders.each says "for each order"; a while makes you decode the counter.
  • Works on anything with each: arrays, hashes, ranges, files, database results and your own classes.
  • Safe scope. Block variables do not leak into the surrounding method.

Use while and loop (see Loops) when the number of repetitions depends on a condition rather than on a collection.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 5.times { |i| ... } pass to the block as the first value of i?

    times counts from zero up to one less than the number, which matches array indexes.
  2. 2. What does [1, 2, 3].each { |n| n * 2 } return?

    each always returns the receiver. Use map to get the transformed values.
  3. 3. How do you count from 1 while iterating an array with each?

    each without a block returns an enumerator, and with_index(1) starts the counter at 1.
  4. 4. What does it mean inside a block in Ruby 3.4 and later?

    it is an implicit name for the single block argument, so [1, 2].map { it * 2 } works without naming the parameter.
  5. 5. Which statement about variables created inside a block is true?

    A variable first assigned inside a block lives only inside it. Outer variables are shared with the block.

Summary

  • An iterator is a method that runs your block repeatedly: each, times, upto, downto, step, each_with_index, each_char, each_slice and more.
  • Blocks use { } for one line and do ... end for several lines. Parameters go between |bars|.
  • Block parameters are lenient: extra values are ignored, missing ones are nil, an array is spread over several parameters.
  • Variables created in a block are local to it. Outer variables are shared.
  • it (Ruby 3.4+) and _1, _2 name block arguments implicitly.
  • next skips a pass, break stops the iteration, and each returns the receiver.

Next: Ranges