Exploring Proc and Lambda in Ruby

BharteeTechRubyOnRails
2 min readJun 11, 2023

--

Proc and Lambda are objects in Ruby that represent anonymous functions or blocks of code.

Proc:

A Proc is an instance of the Proc class in Ruby.

It can be created using the proc method or by using the lambda keyword (which creates a Proc object with slightly different behavior, as explained below).

A Proc can be thought of as a "saved block" or a closure, as it encapsulates a block of code along with its surrounding context.

A Proc does not enforce strict argument checking, meaning it can be called a different number of arguments than defined.

my_proc = proc { puts "Hello, World!" }
=> #<Proc:0x00005606f7de2bd8 (irb):1>

3.0.0 :002 > my_proc.call
Hello, World!
=> nil

Lambda:

A Lambda is an instance of the Proc class as well, but with slightly different behavior compared to a regular Proc.

It is created using the lambda keyword or the -> syntax.

A Lambda enforces strict argument checking, meaning it expects the exact number of arguments specified.

A Lambda uses a return statement to return a value only from the lambda itself, without affecting the enclosing scope.

 my_lambda = lambda { |name| puts "Hello, #{name}!" }
=> #<Proc:0x00005606f7e1b708 (irb):3 (lambda)>

3.0.0 :004 > my_lambda.call("Alice")
Hello, Alice!
=> nil

Proc and Lambda Example:

my_proc = proc { |x, y| x + y }
=> #<Proc:0x00005606f890a628 (irb):32>

my_lambda = ->(x, y) { x + y }
=> #<Proc:0x00005606f8a2d4b0 (irb):33 (lambda)>

proc_result = my_proc.call(1)
(irb):32:in `+': nil can't be coerced into Integer (TypeError)
from (irb):32:in `block in <top (required)>'
from (irb):34:in `<main>'

lambda_result = my_lambda.call(1)
(irb):33:in `block in <top (required)>': wrong number of arguments (given 1, expected 2) (ArgumentError)
from (irb):35:in `<main>'

proc, the code will execute without raising an error. The argument 1 will be assigned to x, while y will be nil. As a result, when trying to add 1 + nil, it will return nil, and you will see nil printed to the console.

lambda, an ArgumentError will be raised with the message "wrong number of arguments (given 1, expected 2)". The lambda enforces strict argument checking and expects exactly two arguments.

--

--

BharteeTechRubyOnRails
BharteeTechRubyOnRails

Written by BharteeTechRubyOnRails

Ruby on Rails Developer || React Js || Rspec || Node Js

No responses yet