如何在 ruby 中提早 return 来减少嵌套 if?

How do I do early return in ruby to reduce nested if?

我总是使用早期 return 来减少嵌套 if(使用其他语言编程),如下所示:

//instead of nested if like this 
if (condition1) {
   if (condition2) {
     if (condition3) {
       //... finally meet all conditions 
       //do the job 
     }
   }
}
//return early 
if (!condition1) {
   //clean up resource in step #1
   return
}
if (!condition2) {
   //clean up resource in step #2
   return
}
if (!condition3) {
   //clean up resource in step #2
   return
}
...
//finally meet all conditions 

但是在 ruby 中提早 return 怎么办?我不能在 Ruby 中的 if 块中 return。我收到错误

"Uncaught exception: unexpected return ... `block (2 levels) in ': unexpected return (LocalJumpError)"

----更新-----

抱歉,我忘了说在像这样的简单情况下它是有效的

def early(input)
  if (input <0)
    puts 'should >0'
    return
  end
  puts 'good'
end

我正在学习 Fiber,我使用 https://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/

中的示例
def http_get(url)
  f = Fiber.current
  http = EventMachine::HttpRequest.new(url).get

  # resume fiber once http call is done
  http.callback { f.resume(1,http) }
  http.errback  { f.resume(2,http) }

  return Fiber.yield
end

EventMachine.run do
  Fiber.new{
    result = http_get('https://www.google.com/')
    if (result[0] ==2) 
      puts "error"
      return # using break has the error 'break from proc-closure (LocalJumpError)' too 
    end
    result = http_get('https://www.google.com/search?q=eventmachine')
    page = result[1]
    puts "Fetched page 2: #{page.response}"
  }.resume
end

我收到错误消息。

----更新2----

根据我得到的答案和评论,我发现了这个 How can I return something early from a block?

Why does the break statement in ruby behave differently when using Proc.new v. the ampersand sign? 解释了为什么 break 也不起作用。引用 "break is supposed to make the caller of the block return, but Proc.new has already returned."

return vs break vs next 绝对是 ruby 新手的障碍

使用next而不是return提前退出内部块:

class A 
  def run 
    yield
  end
end

a = A.new
a.run do 
  puts "ola"
  next
  puts "hello"
end

为了使用return,它应该直接放在方法体内。

但是当你将块传递给函数时,使用 EventMachine.run doFiber.new{,块内的代码不直接在函数内,而是作为参数传递给不同的功能。在块内你不能调用 return,但你可以使用 next.

提前退出

我猜设计者决定这样做的原因是因为块内的 return 会导致混淆是块 return 还是整个方法。