加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:57:43 所属栏目:百科 来源:网络整理
导读:x = StandardError.new(:hello)y = StandardError.new(:hello)x == y # = truex === y # = truebegin raise xrescue x puts "ok" # gets printedendbegin raise xrescue y puts "ok" # doesn't get printedend 为什么不打印第二个“ok”?我无法弄清楚.我已
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}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读