Blocks in Ruby

Learn about code blocks and how we can use them in Ruby,

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 ...