Introduction
Ruby is a general-purpose, dynamic, reflective, object-oriented programming language. Everything in Ruby is an object. Ruby's development aimed to create a user interface between human programmers and the underlying computational machinery.
As there are closures in different programming languages, Ruby have blocks. A block in Ruby is similar to a method but does not belong to an object.
Let’s learn about Blocks in Ruby in-depth.
Blocks in Ruby
In Ruby, a block is similar to a method. Ruby blocks enable us to execute any calculations and manipulation in the same manner as we would inside of any method. Therefore, we can say that while blocks in Ruby are identical to any method, they do not belong to any objects.
Properties of blocks:-
1.) Block can take arguments and return a value.
2.) Block does not have a unique name.
3.) Blocks are made of pieces of code.
4.) A block can be passed to a method call or is always called with a function.
5.) The yield statement is used to invoke a block within a method with a value.
6.) Blocks can be called from within the method they are passed to, just like methods can.
In Ruby, there are three different types of Blocks:-
1.) do and end statement blocks: The most typical way of creating any block in Ruby is this one. With the help of do, we may create repetition-based code and obtain each attribute.
2.) Inline blocks or with Curly braces: In Ruby, curly braces can be used to create any block, and inside of them, codes or codes for the compilation of certain task blocks can be written.
3.) Block with arguments: With the help of the || symbol, we may pass the block with certain arguments.
Syntax of Ruby Blocks:
The Ruby block syntax can be divided into three distinct sections.
1.) Inside the do…end statement Syntax:
block_name do
#statement-1
#statement-2
#statement-3
.
.
.
end
2.) Inline blocks between the curly braces {} Syntax:
block_name { #statements_to_be_executed }
3.) Block with arguments enclosing between the pipe or vertical bars || Syntax:
block_name do |arguments|
#statement-1
#statement-2
#statement-3
.
.
.
end
or
block_name {|arguments| #statements_to_be_executed }