Closures In Ruby: Lambdas & Procs

Closures In Ruby: Lambdas & Procs
Social sharing

Ruby handles Closures in a rather unique way, with Lambdas & Procs being two of the most powerful features.

A Closure basically has the following properties:

  • Can be passed around like an object
  • Remembers values of all the variables that were in scope.
  • Accesses the variables when called, even if they may no longer be in scope.

In Ruby, Closures are supported through Procs and Lambdas.

Contents

How Are These Objects Different?

The basic difference is in terms of returning the objects and argument passing. Lambdas check the number of arguments, while Procs don’t.

Here’s the code snippet for Lambdas:

myblock = lambda { |p| puts p }  
$> myblock.call(5)                   
#output: 5
$> myblock.call                      
#output: ArgumentError: wrong number of arguments (0 for 1)

But, in case of Procs:

proc= Proc.new { |p| puts p }  
$> proc.call(5)                   
#output: 5
$> proc.call                      
#output: returns nil
$> proc.call(5,4,3)  
 #output: prints out 5 and forgets about the extra arguments

Lambdas and procs treat the ‘return’ keyword differently. Here’s an example that uses Lambdas:

def sample_method
 lambda { return "Return me from the block here" }.call
 return "Returning from the calling method"
end
$> puts sample_method

Output: Returning from the calling method

Here’s another example using Proc.new:

def my_method
 Proc.new { return "Return me from the block here" }.call
 return "Returning from the calling method"
end
$>puts my_method

Output: Return me from the block here.

Did I miss anything out? Please share your thoughts at [email protected].

I would also appreciate it, if you leave your suggestions/feedback below.

Your recently viewed posts:

Jayadev Das - Post Author

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘About Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!

    Contact Us

    We’d love to help & work with you




    When do you want to start ?


    Enter your email address to stay up to date with the latest news.
    Holler Box

    Orange Exit pop up

    Subscribe for the latest
    trends in web and
    mobile app development
    Holler Box

    Exit pop up

    Sad to see you leaving early...

    From "Aha" to "Oh shit" we are sharing everything on our journey.
    Enter your email address to stay up to date with the latest news.
    Holler Box