在Ruby块中使用“返回" [英] Using 'return' in a Ruby block
问题描述
我正在尝试将Ruby 1.9.1用于嵌入式脚本语言,以便将最终用户"代码写入Ruby块中.与此相关的一个问题是,我希望用户能够在块中使用'return'关键字,因此他们不必担心隐式的返回值.考虑到这一点,这是我想做的事情:
I'm trying to use Ruby 1.9.1 for an embedded scripting language, so that "end-user" code gets written in a Ruby block. One issue with this is that I'd like the users to be able to use the 'return' keyword in the blocks, so they don't need to worry about implicit return values. With this in mind, this is the kind of thing I'd like to be able to do:
def thing(*args, &block)
value = block.call
puts "value=#{value}"
end
thing {
return 6 * 7
}
如果在上面的示例中使用"return",则会收到LocalJumpError.我知道这是因为所讨论的块是Proc而不是lambda.如果删除"return",该代码将起作用,但在这种情况下,我真的更希望能够使用"return".这可能吗?我尝试将块转换为lambda,但结果是相同的.
If I use 'return' in the above example, I get a LocalJumpError. I'm aware that this is because the block in question is a Proc and not a lambda. The code works if I remove 'return', but I'd really prefer to be able to use 'return' in this scenario. Is this possible? I've tried converting the block to a lambda, but the result is the same.
推荐答案
在这种情况下只需使用next
:
Simply use next
in this context:
$ irb
irb(main):001:0> def thing(*args, &block)
irb(main):002:1> value = block.call
irb(main):003:1> puts "value=#{value}"
irb(main):004:1> end
=> nil
irb(main):005:0>
irb(main):006:0* thing {
irb(main):007:1* return 6 * 7
irb(main):008:1> }
LocalJumpError: unexpected return
from (irb):7:in `block in irb_binding'
from (irb):2:in `call'
from (irb):2:in `thing'
from (irb):6
from /home/mirko/.rvm/rubies/ruby-1.9.1-p378/bin/irb:15:in `<main>'
irb(main):009:0> thing { break 6 * 7 }
=> 42
irb(main):011:0> thing { next 6 * 7 }
value=42
=> nil
-
return
总是从方法返回,但是如果您在irb中测试此代码片段,则您没有方法,这就是为什么拥有LocalJumpError
的原因
-
break
从块返回值并结束其调用.如果您的代码块是由yield
或.call
调用的,则break
也会从此迭代器中断 -
next
从块返回值并结束其调用.如果您的代码块是由yield
或.call
调用的,则next
将值返回到调用yield
的行 return
always returns from method, but if you test this snippet in irb you don't have method, that's why you haveLocalJumpError
break
returns value from block and ends its call. If your block was called byyield
or.call
, thenbreak
breaks from this iterator toonext
returns value from block and ends its call. If your block was called byyield
or.call
, thennext
returns value to line whereyield
was called
这篇关于在Ruby块中使用“返回"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!