Sonntag, 13. Juli 2014

Differ between Proc and lambda in Ruby!

First of all there is no difference between a Proc (read Do the Proc! ... a Ruby closure) and a lambda (read Have a lambda! ... a Ruby closure) in Ruby, technically spoken. Both are Proc objects: {}
=> #<Proc:0x000000029642c0@(irb):1>
lambda {}
=> #<Proc:0x000000029642c0@(irb):2 (lambda)>
but with a different flavor (please note the second object stringification).
Well, but that's not the only difference (otherwise having 2 equal closure types in Ruby would not make any sense).
The differences are:
  1. lambda check the number of arguments and Procs do not.
  2. Proc and lambda treat return differently
A lambda checks the number of arguments:
lamda = lambda { |language| puts language } 'Ruby'          # prints Ruby                 # ArgumentError: wrong number of arguments (0 for 1) 'Ruby', 'Java'  # ArgumentError: wrong number of arguments (2 for 1)
unlike the Proc:
proc = { |language| puts language } 'Ruby'          # prints Ruby                 # prints nothing 'Ruby', 'Java'  # prints Ruby, but ignores Java
In terms of the second difference, a lambda returning something explicitly, will not force the environment (of the closure) to return either:
def lambda_environment
  lamda = lambda { return }
  puts 'Ruby'
lambda_environment # prints Ruby
The lambda returns into its environment and let it end its processing.
But the Proc does not:
def proc_environment
  proc = { return }
  puts 'Ruby'
proc_environment # does not print anything
The Proc forces its environment to return immediately. Further articles of interest:

Supported by Ruby 2.1.1