Ruby Block: Building Complex Programs with Simple Blocks

Ruby BlockRuby was developed almost two decades ago, incorporating features from several of the most popular languages of the day, like Perl, Smalltalk, Python, Lisp and Eiffel. It was designed to be easy to pick up for programmers who were used to working with other languages, like C or C++. Ruby is a true object oriented language, and it has a nifty memory allocation feature and a dynamic type system. The language supports multiple programming paradigms- it is object-oriented, functional and imperative-, which makes it powerful and suitable for all kinds of programming needs.

Today, Ruby is the 13th most popular programming language in the world. The Ruby on Rails framework, which is based on the language, is used to design applications for the internet. You will find it easy to learn Ruby if you have learned a programming language in the past. Ruby is also one of the easiest first languages to learn. Ruby lets you do more with less- the amount of code you need to type in Ruby to get things done is much less than what you need to type if you use another language. If you want to learn Ruby, you can take on this Ruby course which is specially designed for those who do not have prior programming experience. If you just need a quick catch up, you can read this step by step Ruby tutorial instead.

Ruby Blocks

In this tutorial, we’ll give you a brief overview of the concept of blocks in Ruby. Some basic knowledge of the language is necessary to understand this tutorial. If you’re new to Ruby, now would be a good time to take this beginners course.

A block is a very useful tool provided by Ruby. Blocks are similar to methods in the language. In fact, they can be associated with a method – they can be defined after the final parameter of a method call. So what is a block exactly? A block is a collection of code (a block of code) that is enclosed within braces. It has a name that is used to invoke the code within the braces. For example, if your block is named “exampleblock” and you wanted to invoke it, you would use a function called “exampleblock” that has an identical name. The syntax of a simple block is as follows:

name_of_block {
statement 1
statement 2
statement 3
}

A block can be paired with a single or multiple statements. You can use the yield statement with a value to invoke a block – that is, the yield statement helps you associate a method with a block. Let’s take a look at how a yield statement can be used with a block in Ruby.

Using Yield to Associate a Block with a Method

Let’s write a simple program that uses the yield statement and includes a method and a block. The name of the block in the program is “exampleblock”, and the name of the method will be the same as the name of the block:

#!/usr!/bin/ruby
def exampleblock
puts “This is a line of text”
yield
puts “This is a second line of text”
yield
puts “This is a third line of text”
end
exampleblock {puts “This is the yield statement output”}

The output of the following program will be as follows:

This is a line of text
This is the yield statement output
This is the second line of text
This is the yield statement output
This is the third line of text

Does it look complicated? It’s actually very simple. First, we defined a block called exampleblock. Then we asked Ruby to display a simple string “This is a line of text”. Then we used the yield keyword. What does the yield keyword do? It checks the chunks of code that is associated with the exampleblock block. In this case, the code is a simple message: “This is the yield statement output”. Every time you use the yield keyword, the code associated with the example block will get executed. Because we used yield 2 times in the program, the simple message “This is the yield statement output” will get displayed 2 times. To see more Ruby programming examples, check out this Ruby practical training.

Using the Yield Statement to Pass Parameters

The yield statement can be used to pass parameters to a block. You can pass multiple parameters if necessary. What parameters are we talking about exactly? Parameters that can be fit into the code that is contained in a block and which are necessary to execute the block.

Take a look at this example program. Once again, we are defining a block called “exampleblock” and pairing it with the yield statement:

#!/usr/bin/ruby
def exampleblock
yield 100
yield 200
yield 300
puts “Each yield statement passes a different parameter”
end
exampleblock { |i| puts “This yield statement has passed the parameter #{i}”}

Output: The output of this program is as follows:

This yield statement has passed the parameter 100
This yield statement has passed the parameter 200
This yield statement has passed the parameter 300
Each yield statement passes a different parameter

The program is simple enough to understand. Each yield statement has been assigned a different parameter. Our exampleblock block accepts a parameter each time the yield statement is invoked and it’s used in the code that is being executed.

The yield statement can be used to pass multiple parameters. For example, if you wanted to pass 3 integer (number) parameters, the yields statement and the block would have looked something like this:

yield 100, 200, 300
exampleblock {|i, i, i| code to be run}

Including Multiple Blocks in a Program

A program may include multiple blocks in Ruby. If you want to use two or more blocks in a program, you can use the BEGIN and END keywords. The BEGIN keywords tells Ruby that the BEGIN block (which is the code that is contained in the braces {} after the BEGIN keyword) should be executed at the start of the program. If there are two or more BEGIN blocks, then Ruby will execute them in the order they are found. The END keyword tells Ruby to execute the END block (and code) at the end of the program. If there are two or more END keywords, then Ruby will execute them in the reverse order.

Let’s take a simple program to explain this concept in a little more depth:

#!/usr/bin/ruby
END {
  # END block code
  puts "This is the end block"
}
BEGIN {
  # Will be executed first
  puts "This is the first BEGIN block"
}
BEGIN {
# Will be executed second
puts “This is the second BEGIN block”
}
# This is the body of the program
puts "This is the body of the program"

Output:

This is the first BEGIN block
This is the second BEGIN block
This is the body of the program
This is the END block

As we explained earlier, Ruby will execute the BEGIN blocks in the order it finds them in. The END block will be executed last, no matter where it is placed in the program – in our program, it’s placed at the start, but will still be executed last. Any other code you have written will be executed after the BEGIN blocks and before the END block.

Blocks are a very useful and fun feature of the language. We recommend that you try out the programs we’ve give here for yourself to get a better hang of the concepts. If you are having trouble with these programs or if you just want to learn more about blocks (and other concepts) in more detail, you can sign up for this comprehensive Ruby course. Once you’re ready to take it up a notch, sign up for this advanced course and set sail to master Ruby!