Table of Contents
In this article, I will take you through the difference between Ruby blocks and Procs.
Ruby Blocks and Procs
Blocks
a)A Block Consists of Chunk of Code
b)Block has a name
c)Codes in the block is always enclosed within braces
d)A block is always invoked from a function with the same name as that of the block.
e)We invoke a block using yield statement.
Procs
a)PROC class can turn block into an object by wrapping blocks in its instance.
b)Proc objects are blocks of code that have been bound to a set of local variables.
c)This turns our block into a first class function and then we can perform all sorts of things with Blocks as we can do with a normal object.
Four ways to create a Proc Object
a)Using Proc.new
b)Using the Proc method in kernel module
c)Using the kernel lambda methods
d)By two implicit ways
-Using YIELD Statement
-Using Concept of &BLOCK
Converting between a blocks and Procs
Another common thing you will see in Ruby code is using the & operator to convert between blocks to Procs and Procs to blocks.
For example, imagine we have this method:
def do_something(&block) block.call end
When this method is called with a block, the block will be converted into a Proc. You can then use the block as if it were a Proc inside of the method:
do_something { puts "hello"}
Also Read: How to Install Docker on CentOS 7
References: Ruby Documentation