Back

lambda v.s. Proc.new (lambda 与 proc的区别)

发布时间: 2014-01-05 00:29:00

refer to: <<metaprogramming ruby>>, page 108~113.

1. lambda中可以有显式的return , Proc不行。前者表示仅仅从当前的lambda中返回,而后者会出错 ( you can write return in lambda , but not in Proc.new. the former means return from a lambda an continue execute the code in the caller, but the latter means just return from the caller and will cause an error ) the root cause is:

def double callable_object
  callable_object.call * 2
end

my_block = lambda { return 10 }
double my_block # => 20  

my_proc = Proc.new { 10 }
double my_proc # => OK, 20 

error_proc = Proc.new { return 10 }
double my_proc # =>   unexpected return (LocalJumpError) 

2. 对于Arity 的处理不同. 如果传入的参数跟 block声明的参数数量不同的话,lambda直接报错,而proc会容错。( lambda raises error if the arity is not match, but the Proc.new won't ) 

my_lambda = lambda { |x| return x }
my_lambda.call   # => Argument Error,   0 for 1
my_lambda.call(10) # => 10
my_lambda.call(10,20, 30 ) # => Argument Error,   3 for 1

my_proc = Proc.new { |x| x }
my_proc.call  # => nil
my_proc.call(10) # => 10
my_proc.call(10,20) # => 10

Back