我总是使用提前返回来减少嵌套 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 中提前返回?我无法在 Ruby 的 if 块内返回。我得到了错误
“未捕获的异常:意外返回......'块(2级)':意外返回(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 ----
有了我得到的答案和评论,我发现了这个如何从一个块中提前返回一些东西?
这为什么在使用 Proc.new v. & 符号时,ruby 中的 break 语句表现不同?解释了为什么 break 也不起作用。引用“break 应该使块的调用者返回,但 Proc.new 已经返回。”
return vs break vs next 绝对是 ruby 新手的障碍