ruby 块并从块中返回一些东西 [英] ruby block and returning something from block

查看:43
本文介绍了ruby 块并从块中返回一些东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 ruby​​ 1.8.7.

I am using ruby 1.8.7.

p = lambda { return 10;}
def lab(block)
  puts 'before'
  puts block.call
  puts 'after'
end
lab p

以上代码输出为

before
10
after

我将相同的代码重构为这个

I refactored same code into this

def lab(&block)
  puts 'before'
  puts block.call
  puts 'after'
end
lab { return 10; }

现在我收到 LocalJumpError:意外返回.

Now I am getting LocalJumpError: unexpected return.

对我来说,这两个代码都在做同样的事情.是的,在第一种情况下我传递了一个过程,在第二种情况下我传递了一个块.但是 &block 将该块转换为 proc.所以 proc.call 应该表现相同.

To me both the code are doing same thing. Yes in the first case I am passing a proc and in the second case I am passing a block. But &block converts that block into proc. So proc.call should behave same.

是的,我看过这篇文章在 Ruby 块中使用返回"

推荐答案

当您使用 & 传入块时,您将其转换为 proc.重要的一点是a proc 和a lambda 是不同的(lambda 实际上是proc 的一个子类),特别是它们如何处理返回.

When you pass in the block with &, you're converting it to a proc. The important point is that a proc and a lambda are different (lambda is actually a subclass of proc), specifically in how they deal with return.

所以你重构的代码实际上相当于:

So your refactored code is actually the equivalent of:

p = Proc.new { return 10;}
def lab(block)
  puts 'before'
  puts block.call
  puts 'after'
end
lab p

这也会产生一个 LocalJumpError.

which also generates a LocalJumpError.

原因如下:proc 的返回从其词法范围返回,而 lambda 返回到其执行范围.因此,当 lambda 返回到 lab 时,传入它的 proc 返回到声明它的外部作用域.局部跳转错误意味着它无处可去,因为没有封闭函数.

Here's why: A proc's return returns from its lexical scope, but a lambda returns to its execution scope. So whereas the lambda returns to lab, the proc passed into it returns to the outer scope in which it was declared. The local jump error means it has nowhere to go, because there's no enclosing function.

Ruby 编程语言说得最好:

Proc 具有类似块的行为,而 lambdas 具有类似方法的行为

Procs have block-like behavior and lambdas have method-like behavior

您只需要跟踪您在何处使用的内容.正如其他人所建议的那样,您需要做的就是从您的块中删除 return,一切都会按预期进行.

You just have to keep track of what you're using where. As others have suggested, all you need to do is drop the return from your block, and things will work as intended.

这篇关于ruby 块并从块中返回一些东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆