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 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
10 times, we can take advantage of Ruby code blocks and pass the block to some function. In this case, the program can be written in one line, instead of ten. -
Code can either be executed or not, depending on some conditions. Sometimes, the decision isn’t even up to a programmer. There could be some circumstances for the code to be executable or not. In other words, if we see a code block, that doesn’t mean that it will be executed without fail.
Syntax for code blocks in Ruby can be done in two ways:
-
If the block is large and it takes up multiple lines, we should use the keywords
do
andend
. -
If it’s only one line, we can use curly braces:
{
and}
.
The result will be the same if either of these syntaxes is used. Curly braces work great for simple expressions, and do
and end
allow us to put as many lines as we want between them. Keep in mind that, usually, huge code blocks are not recommended.
Let’s try to use code blocks and see what happens:
Get hands-on with 1400+ tech skills courses.