加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 21:54:30 所属栏目:百科 来源:网络整理
导读:我有很多麻烦,了解返回在块,procs和lambdas中的工作原理. 例如,在以下情况下,为什么batman_ironman_proc工作,而batman_yield会抛出错误? def batman_ironman_proc victor = Proc.new { return "Batman will win!" } victor.call "Iron Man will win!"enddef
我有很多麻烦,了解返回在块,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读