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.new {}
=> #<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 }
lamda.call 'Ruby'          # prints Ruby
lamda.call                 # ArgumentError: wrong number of arguments (0 for 1)
lamda.call 'Ruby', 'Java'  # ArgumentError: wrong number of arguments (2 for 1)
unlike the Proc:
proc = Proc.new { |language| puts language }
proc.call 'Ruby'          # prints Ruby
proc.call                 # prints nothing
proc.call '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 }
  lamda.call
  puts 'Ruby'
end
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 = Proc.new { return }
  proc.call
  puts 'Ruby'
end
proc_environment # does not print anything
The Proc forces its environment to return immediately. Further articles of interest:

Supported by Ruby 2.1.1