Ruby中的下一步是什么?

B S*_*ven 3 ruby iterator enumerable

以下代码有效:

collection.each do |i|
  begin
    next if i > 10
    i += 1
  rescue
    puts "could not process #{ i }"
  end
end
Run Code Online (Sandbox Code Playgroud)

但是,当我们重构时:

collection.each do |i|
  begin
    increment i
  rescue
    puts "could not process #{ i }"
  end
end

def increment i
  next if i > 10
  i += 1
end
Run Code Online (Sandbox Code Playgroud)

我收到invalid next错误.这是Ruby(1.9.3)的限制吗?

begin rescue如果increment方法中有异常,块是否以相同的方式工作?

Chr*_*ton 10

您的next陈述必须在循环内发生.你的increment方法里面没有循环.

异常将"冒泡",因此如果您的increment方法中存在异常,它将被rescue调用方法的部分捕获.