DEV Community

Cover image for Block, Lambda, and Proc in Ruby
shiva kumar
shiva kumar

Posted on

Block, Lambda, and Proc in Ruby

Block

Blocks are pieces of code between {} or do and end keywords. We can pass parameters in the block. Blocks are not object.

{ puts 'Hola, I'm a block'} 
Enter fullscreen mode Exit fullscreen mode

or

do 
  puts 'Hola, I'm a block'
end
Enter fullscreen mode Exit fullscreen mode

Proc

Block can be converted to objects using Proc. Proc is assigned to a variable and its executed by using .call method.Proc can be defined using

Proc.new {}
Enter fullscreen mode Exit fullscreen mode

or

proc {}
Enter fullscreen mode Exit fullscreen mode

Proc accepts arguments but it doesn't throw an error when called with a lesser or more argument than expected

my_proc = Proc.new { |x|  "x = #{x}" }
 => #<Proc:0x00007f91ea9eada8@(irb):57>
my_proc.call(2)
=> "x = 2"

my_proc = Proc.new { |x,y,z| "x = #{x}, y = #{y}, z = #{z}" }
 => #<Proc:0x00007f91eaa00e78@(irb):59>
my_proc.call(2,3)
 => "x = 2, y = 3, z = "

my_proc.call([2,3])
 => "x = 2, y = 3, z = "

my_proc.call(2,3,5)
 => "x = 2, y = 3, z = 5"

Enter fullscreen mode Exit fullscreen mode

Lambda

Lambda and Proc are similar. Lambda is a little anonymous function, which can be stored in a variable.Lambda will throw error if arguments passed is less or more than expected just like function

Lambda can be defined using the lambda keyword or -> {}

hello = lambda {"Hola"}

or

hello = -> {"Hola"}
Enter fullscreen mode Exit fullscreen mode

my_lambda = lambda { |x| "x =  #{x}" }

my_lambda.call(2)
2


my_lambda = lambda { |x,y,z| "x = #{x}, y = #{y}, z = #{z}" }

my_lambda.call(2,3)
Traceback (most recent call last):
        7: from /Users/nbt040/.rvm/gems/ruby-2.6.3/bin/ruby_executable_hooks:24:in `<main>'
        6: from /Users/nbt040/.rvm/gems/ruby-2.6.3/bin/ruby_executable_hooks:24:in `eval'
        5: from /Users/nbt040/.rvm/rubies/ruby-2.6.3/bin/irb:23:in `<main>'
        4: from /Users/nbt040/.rvm/rubies/ruby-2.6.3/bin/irb:23:in `load'
        3: from /Users/nbt040/.rvm/rubies/ruby-2.6.3/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        2: from (irb):67
        1: from (irb):66:in `block in irb_binding'
ArgumentError (wrong number of arguments (given 2, expected 3))
Enter fullscreen mode Exit fullscreen mode

Lambda return works like functions. Proc will return from the current context

def lambda_method
 lambda { return "Returned from Lambda block" }.call
 return "return from method"
end

 lambda_method()
 => "return from method"

def proc_method
 Proc.new { return "Returned from the Proc block" }.call
 return "return from method"
end

proc_method()
 => "Returned from the Proc block"
Enter fullscreen mode Exit fullscreen mode

Proc and Lambda behave differently in accepting the argument and how they return. Lambdas are proc but procs are not lambda. Hope this quick guide helped you in understanding Block, Proc and Lambda.

Top comments (0)