如何从红宝石块中突围? [英] How to break out from a ruby block?

查看:26
本文介绍了如何从红宝石块中突围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Bar#do_things:

class Bar   
  def do_things
    Foo.some_method(x) do |x|
      y = x.do_something
      return y_is_bad if y.bad? # how do i tell it to stop and return do_things? 
      y.do_something_else
    end
    keep_doing_more_things
  end
end

这里是Foo#some_method:

class Foo
  def self.some_method(targets, &block)
    targets.each do |target|
      begin
        r = yield(target)
      rescue 
        failed << target
      end
    end
  end
end

我考虑过使用 raise,但我试图让它通用,所以我不想在 Foo 中放置任何特定的东西.

I thought about using raise, but I am trying to make it generic, so I don't want to put anything any specific in Foo.

推荐答案

使用关键字 next.如果不想继续下一项,请使用 break.

Use the keyword next. If you do not want to continue to the next item, use break.

当在块中使用 next 时,它会导致块立即退出,将控制权返回给迭代器方法,然后它可以通过再次调用块来开始新的迭代:

When next is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:

f.each do |line|              # Iterate over the lines in file f
  next if line[0,1] == "#"    # If this line is a comment, go to the next
  puts eval(line)
end

当在块中使用时,break 将控制权移出块,移出调用块的迭代器,并转移到调用迭代器之后的第一个表达式:

When used in a block, break transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:

f.each do |line|             # Iterate over the lines in file f
  break if line == "quit\n"  # If this break statement is executed...
  puts eval(line)
end
puts "Good bye"              # ...then control is transferred here

最后,return 在块中的用法:

And finally, the usage of return in a block:

return 总是导致封闭方法返回,无论它在块中嵌套有多深(除了 lambdas):

return always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):

def find(array, target)
  array.each_with_index do |element,index|
    return index if (element == target)  # return from find
  end
  nil  # If we didn't find the element, return nil
end

这篇关于如何从红宝石块中突围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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