ruby – 这个救援案例有什么问题?

前端之家收集整理的这篇文章主要介绍了ruby – 这个救援案例有什么问题?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
x = StandardError.new(:hello)
y = StandardError.new(:hello)
x == y # => true
x === y # => true

begin
  raise x
rescue x
  puts "ok" # gets printed
end

begin
  raise x
rescue y
  puts "ok" # doesn't get printed
end

为什么不打印第二个“ok”?我无法弄清楚.我已经读过here,ruby使用===运算符来匹配rescue子句的异常,但表面上并非如此.

我正在使用Ruby 1.9.3

编辑:所以看起来像是在提升x之后,x == y和x === y不再持有.似乎是因为x和y no longer have the same backtrace.

解决方法

我只想在表格中添加一些东西:OP代码表明两个例外是相同的但它们不是 – 而且我想说明OP的意思:

So it seems like that after doing raise x,x == y and x === y no longer hold. It seems to because x and y no longer have the same backtrace.

x = StandardError.new(:hello)
 y = StandardError.new(:hello)
 class Object
   def all_equals(o)
     ops = [:==,:===,:eql?,:equal?]
     Hash[ops.map(&:to_s).zip(ops.map {|s| send(s,o) })]
   end
 end

 puts x.all_equals y # => {"=="=>true,"==="=>true,"eql?"=>false,"equal?"=>false}

 begin
   raise x
 rescue
   puts "ok" # gets printed
 end

 puts x.all_equals y # => {"=="=>false,"==="=>false,"equal?"=>false}

猜你在找的Ruby相关文章