Blocks

Pass a chunk of code into a method

7 min read

You have already been using blocks without necessarily calling them by name. Remember the code between do and end in your .each and .times loops? That chunk of code is called a block, and it is one of Ruby's most distinctive features.

What exactly is a block?

A block is a piece of code that you pass into a method, so the method can run it whenever it needs to.

3.times do
  puts "Hi!"
end

Here, the block is everything between do and end. The .times method takes that block and runs it three times.

Two ways to write a block

Ruby offers two styles for writing blocks. The do and end style is common for longer blocks, while curly braces are common for short, one-line blocks.

fruits = ["apple", "banana", "cherry"]
fruits.each { |fruit| puts fruit }

This does exactly the same thing as writing fruits.each do |fruit| puts fruit end, just on one line.

Blocks with .map

Blocks are not only for printing things; they can also transform data. The .map method runs a block on every item in an array and collects the results into a brand new array.

numbers = [1, 2, 3]
doubled = numbers.map { |n| n * 2 }
puts doubled

This prints 2, 4, and 6, because each number in the original array was doubled by the block and placed into the new doubled array. The original numbers array is left completely unchanged.

Do not worry if blocks feel a little abstract at first. The more you practice with .each and .map, the more natural this pattern will feel.

Quick check

Q1 What is the code between do and end called when passed to a method?

Q2 What does calling .map with a block do to an array?

Want to save your progress? It's free.

Create a free account