Ruby 重构嵌套的rescue语句

Ruby 重构嵌套的rescue语句,ruby,rescue,Ruby,Rescue,Rescue语句在连续过滤不同错误时效果良好: o = Object.new begin o.foo rescue ArgumentError puts "Object o does define #foo, but you got the argument number wrong!" rescue NoMethodError puts "Object o does not respond to #foo!" else puts "That's right!" end 但当涉

Rescue语句在连续过滤不同错误时效果良好:

o = Object.new
begin
  o.foo
rescue ArgumentError
  puts "Object o does define #foo, but you got the argument number wrong!"
rescue NoMethodError
  puts "Object o does not respond to #foo!"
else
  puts "That's right!"
end
但当涉及到用不同参数拯救同一错误时,我在代码中使用的是:

o = Object.new
begin
  o.foo
rescue NoMethodError
  begin
    o.bar
  rescue NoMethodError
    begin
      o.quux
    rescue NoMethodError
      warn "Object o responds not to basic methods!"
    end
  end
end

不用说,我不喜欢它。有没有更聪明的方法来实现这一点?

可能这并不能回答您的问题,但在这种情况下,如果
响应了我想调用的方法,我会询问
o
,然后再调用它:

method = [:foo, :bar, :baz].find { |m| o.respond_to?(m) }
if method
  o.public_send(method)
else
  warn "Object o responds not to basic methods!"
end
输出:

Object does not respond to basic methods!
quux method called with [10, :hello, "world"]

这适用于没有定义
#respond#u to_missing?
方法的对象,这是非常常见的——我所看到的使用
#method_missing
的大多数代码都属于这一类。

不,它不属于这一类。Object
o
实际上搜索一个BibTeX文件,如果失败,则尝试另一个文件或另一个搜索,直到选项用尽。所以
#回复?
没有帮助。+1,谢谢你提醒我
定义。。。拯救。。。结束
语法并提供一个
重试使用的示例。
Object does not respond to basic methods!
quux method called with [10, :hello, "world"]