ruby – 在procs,lambdas和block中返回语句

我有很多麻烦,了解返回在块,procs和lambdas中的工作原理.

例如,在以下情况下,为什么batman_ironman_proc工作,而batman_yield会抛出错误?

def batman_ironman_proc
  victor = Proc.new { return "Batman will win!" }
  victor.call
  "Iron Man will win!"
end

def batman_yield
    yield
    "Iron man will win!"
end

victor = Proc.new { return "Batman will win!" }

puts batman_ironman_proc 
#batman_yield(&victor) === This code throws an error.

解决方法

由于 one answer在链接问题中显示:

The return keyword always returns from the method or lambda in the current context. In blocks,it will return from the method in which the closure was defined. It cannot be made to return from the calling method or lambda.

您的第一个例子是成功的,因为您在同一个功能中定义了胜利者,因此在这种情况下返回是合法的.在第二个例子中,胜者是在顶级定义的.那么返回的效果不会是从batman_yield(调用方法)返回,而是从顶层本身(Proc被定义的位置)返回的[如果它是有效的].

说明:当您可以访问块的返回值时(即“块中求值的最后一个表达式的值将作为收益的值传递给该方法” – 根据您的注释),您不能使用返回关键字,由于上述原因.例:

def batman_yield
    value = yield
    return value
    "Iron man will win!"
end

victor = Proc.new { return "Batman will win!" }
victor2 = Proc.new { "Batman will win!" }

#batman_yield(&victor) === This code throws an error.
puts batman_yield(&victor2) # This code works fine.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...