Ruby Programming: Understanding Blocks, Procs, and Lambdas

Explore the concept of Ruby Blocks, Procs, and Lambda

Shubham Rajput
Simform Engineering
3 min readMar 10, 2023

--

Ruby block, procs and lambdas

Blocks are one of the things programmers absolutely love about Ruby.
Ruby code blocks are called closures in other programming languages. They are an extremely powerful feature that allows us to write very flexible code. At the same time, they read very well and they are used all over the place.

Let’s explore blocks and their syntax in detail.

Block

Blocks are composed of code chunks and resemble closures in other programming languages. Block can accept arguments and return a value.

Defining a Block

A block code can be used in two ways:

  1. Inside the do…end statement syntax:
block_name do 
statement-1
statement-2
end

2. Using curly braces {} syntax:

block_name { |arg| "Passed arg:  #{arg} }

Calling a Block

The following example illustrates the simplest way to implement and invoke a block. To invoke the “test” block, use the “yield” statement.

def clarify
puts "Inside Method!"
yield
end

# block
clarify{puts "Inside Block!"}

If a method’s argument is preceded by an ampersand (&), you can pass a block to the method, which will be assigned to the method’s last parameter.

def clarify(&block)
block.call
end
clarify { puts "Hello World!"}

Procs

A Proc object is an encapsulation of a block of code that can be stored in a local variable, passed to a method, another Proc, or invoked directly.

Defining a Proc

square = Proc.new {|x| x**2 }

Calling a Proc

square.call(5) OR square.(5) OR square[5]

Lambda

A lambda is a way to define a block and its parameters using a special syntax. You can save the Lambda into a variable for later use, as it is essentially a special type of Proc object.

Defining a Lambda

addition = lambda {|a, b| a + b}
OR
addition = -> (a, b) { a + b}

Calling a Lambda

addition.call(4, 5)

Procs Vs Lambdas

  1. Procs do not enforce the number of arguments passed to them, while Lambdas will raise an ArgumentError exception if the number of arguments passed is incorrect.
  2. The behavior of the return statement is different in Procs and Lambdas. In Procs, it returns from the current method, whereas in Lambdas, it returns from Lambda itself and executes further statements within the method if has any.
    Example:

Blocks are anonymous functions passed as arguments to methods. Procs and Lambdas are objects representing blocks of code. Procs are flexible in handling arguments, while Lambdas have stricter requirements for arguments and return values. Each of these constructs has unique use cases that can improve the functionality and readability of Ruby code. Mastery of blocks, procs, and lambdas equips one to write efficient and powerful Ruby programs.

So, keep exploring with blocks, and happy coding!

--

--