Menu
Coddy logo textTech

What is a Block?

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 15 of 56.

You've already been writing blocks. Every time you wrote each do |x| ... end, the part between do and end was a block: a chunk of code passed to a method.

[1, 2, 3].each do |n|
  puts n * 2
end

Here, each is a method on the array, and do |n| ... end is the block. each runs the block once for every element, passing it in as n.

Blocks are not separate objects you store in variables, they're tied directly to the method call. A method either gets a block or doesn't, and most iteration methods (each, map, select, times) are designed to take one.

3.times do |i|
  puts "hi #{i}"
end

Calling a method without its block changes what it does. [1,2,3].map with no block returns an enumerator instead of a transformed array, so the block is part of what the method means.

challenge icon

Challenge

Beginner

Read an integer n from input. Use the times method with a block to print the message Iteration <i> for each value of i from 0 up to n - 1.

For input 3, the output is:

Iteration 0
Iteration 1
Iteration 2

Cheat sheet

A block is a chunk of code passed to a method between do |param| ... end:

[1, 2, 3].each do |n|
  puts n * 2
end

Use times to repeat a block n times, with i going from 0 to n - 1:

3.times do |i|
  puts "hi #{i}"
end

Try it yourself

n = gets.to_i

# TODO: use n.times with a block to print each iteration
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow