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:
- lambda check the number of arguments and Procs do not.
- Proc and lambda treat return differently
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 JavaIn 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 RubyThe 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 anythingThe Proc forces its environment to return immediately. Further articles of interest:
Supported by Ruby 2.1.1
Keine Kommentare:
Kommentar veröffentlichen