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.