What Are Blocks

Learn about blocks and how they are used.

Defining blocks

Blocks are likely one of Ruby’s most beloved and powerful features. They allow us to write very flexible code. They also read very well and are used all over the place. Moreover, blocks can only be created by the way of passing them to a method when the method is called.

So, what’s a block?

A block is a piece of code that accepts arguments and returns a value. A block is always passed to a method call.

Let’s jump right in.

Example

Press + to interact
5.times do
puts "Oh, hello from inside a block!"
end

Explanation

  • Notice that times is a method defined by numbers. The 5.times block calls the times method on the number 5.
  • Now, when this method is called, the only thing passed to it is a block. That’s the anonymous piece of code between do and end. Other than a block, there are no objects passed as arguments to the times method.
  • The times method is implemented in such a way that it simply executes the block five times, and thus when we run the code, it prints out the message "Oh, hello from inside a block!" five times.

This is pretty much how the times method works on numbers and how blocks work. The times method takes the block (instructions) and runs it as many times as the value of the number on which it’s called.

That the code reads almost like an English sentence is part of the reason why Ruby programmers love blocks.

Block oddities

  • Blocks are anonymous chunks of code.
  • Blocks are passed to methods just like other objects.
  • Blocks can still be executed, just like methods, from inside the method it was passed to.

To summarize: Methods can not only accept input in the form of objects passed as arguments, but they can also accept this one special piece of input, which is an anonymous block of code. They can then execute this block of code to do useful things with it.