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在链接问题中显示:
您的第一个例子是成功的,因为您在同一个功能中定义了胜利者,因此在这种情况下返回是合法的.在第二个例子中,胜者是在顶级定义的.那么返回的效果不会是从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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |