在 Ruby 块中使用“返回" [英] Using 'return' in a Ruby block

查看:30
本文介绍了在 Ruby 块中使用“返回"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 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 have LocalJumpError
    • break returns value from block and ends its call. If your block was called by yield or .call, then break breaks from this iterator too
    • next returns value from block and ends its call. If your block was called by yield or .call, then next returns value to line where yield was called
    • 这篇关于在 Ruby 块中使用“返回"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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