Proc和Lambda的区别在网上没找到能说明白的文字
写写我自己的理解吧以免得忘记了还要再想
Proc和lambd都相当于定义一个代码块,然后这个代码块可以在需要用到的时候通过call(x,y,*z)来唤醒,但是他们的区别在于Proc中的代码影响到当前调用它的方法,而lambd中的代码只会在自己的代码块中起作用,如下一个广为传播的例子能够解释,我这里引用一下.
输出
输出
写写我自己的理解吧以免得忘记了还要再想
D:\>qri Proc
------------------------------------------------------------ Class: Proc
+Proc+ objects are blocks of code that have been bound to a set of
local variables. Once bound, the code may be called in different
contexts and still access those variables.
D:\>qri lambda
---------------------------------------------------------- Kernel#lambda
proc { |...| block } => a_proc
lambda { |...| block } => a_proc
------------------------------------------------------------------------
Equivalent to +Proc.new+, except the resulting Proc objects check
the number of parameters passed when called.
Proc和lambd都相当于定义一个代码块,然后这个代码块可以在需要用到的时候通过call(x,y,*z)来唤醒,但是他们的区别在于Proc中的代码影响到当前调用它的方法,而lambd中的代码只会在自己的代码块中起作用,如下一个广为传播的例子能够解释,我这里引用一下.
def foo
f = Proc.new { return "return from foo from inside proc" }
puts f.call #call的时候已经执行了return,所以foo方法执行完毕
return "return from foo"#不会执行到这一句
end
def bar
f = lambda { return "return from lambda" ;puts "continue?"}
puts f.call #return只在(lambda)f这个块中返回,它后面这句puts "continue?"不会执行到
return "return from bar"#这句话还会执行到,因为lambda中的return并没有影响到bar方法
end
puts foo
输出
return from foo from inside proc
puts bar
输出
return from lambda
return from bar