关于两者的差异,有篇文章提到: “lambda 和 Proc 是一样的,除了 Proc 的 return 会跳出调用的方法,lambda 则不会,它只是返回自己。” 下面的代码证明了这段话的正确。
def foo
f = Proc.new { return "return from foo from inside proc" }
f.call # control leaves foo here
return "return from foo"
end
def bar
f = lambda { return "return from lambda" }
puts f.call # control does not leave bar here prints "return from lambda"
return "return from bar"
end
puts foo # prints "return from foo from inside proc"
puts bar # prints "return from bar"
======= 但是,我验证下面的代码,就感觉有些疑惑了。
def call_block(&block)
block.call(1)
block.call(2)
block.call(3)
end
proc_1 = Proc.new { |i| puts "#{i}: Blocks are cool!" }
proc_2 = lambda { |i| puts "#{i}: Blocks are cool!" }
call_block(&proc_1)
call_block(&proc_2)
输出:
1: Blocks are cool!
2: Blocks are cool!
3: Blocks are cool!
1: Blocks are cool!
2: Blocks are cool!
3: Blocks are cool!
从上面的输出可见,不管是 proc 或者 lambda 均顺序执行玩三个 call 并输出了结果,而没有退出? 疑惑就是,按第一段代码的逻辑,call_block(&proc_1) 应该在执行完 block.call(1) 后退出方法才对,怎解?谢谢!