proc return 与 lambda return
proc return vs lambda return
为什么 Proc 在 ruby return 中执行调用 Proc 的方法中的剩余代码之前?
def hello
a = Proc.new{ return }
a.call
puts "Hello"
end
def proc
hello
puts "Proc"
end
此处return
将跳过puts "Hello"
并仅打印puts "Proc"
但是 lambda
也打印 puts "Hello"
。
这是什么原因?
你应该在这个答案中看到评论 。
上面写着
A lambda is an anonymous method. Since it's a method, it returns a
value, and the method that called it can do with it whatever it wants,
including ignoring it and returning a different value.
A Proc is like
pasting in a code snippet. It doesn't act like a method. So when a
return happens within the Proc, that's just part of the code of the
method that called it
为什么 Proc 在 ruby return 中执行调用 Proc 的方法中的剩余代码之前?
def hello
a = Proc.new{ return }
a.call
puts "Hello"
end
def proc
hello
puts "Proc"
end
此处return
将跳过puts "Hello"
并仅打印puts "Proc"
但是 lambda
也打印 puts "Hello"
。
这是什么原因?
你应该在这个答案中看到评论 。
上面写着
A lambda is an anonymous method. Since it's a method, it returns a value, and the method that called it can do with it whatever it wants, including ignoring it and returning a different value.
A Proc is like pasting in a code snippet. It doesn't act like a method. So when a return happens within the Proc, that's just part of the code of the method that called it