Search⌘ K

Blocks in Ruby

Explore how Ruby's code blocks work and how you can pass them to methods for flexible code execution. Understand when and why to use blocks, how to write multi-line or single-line code blocks using do-end or curly braces, and see practical examples like loops and repeated actions. Gain foundational knowledge of this core Ruby concept to write cleaner, more efficient programs.

We'll cover the following...

Code blocks

Ruby has its own definition of a code block. Usually, when we look at a program, we can visually separate blocks or chunks of code. For example, the first 3 lines are responsible for user input, the next 5 lines for output, and so on. Even though we can call these lines blocks of code from a purely visual point of view, there are code blocks in Ruby with special meanings.

A code block in Ruby is part of a program that we pass somewhere, usually to a function, so it will get executed under some circumstances. We may wonder why we need to pass it when we can execute the block right away. The answer lies in the fact that passing a code block to a function makes sense in the following cases:

  • This code needs to be executed a certain number of times. For example, we want to show the message “Boston Red Sox Are World Champions!” 10 times. Instead of just using puts ...