我有一个类,我想在 case 语句中与字符串和符号进行比较,所以我认为我只是为我的类覆盖了 ===() 方法,所有这些都是黄金。但是,我的 ===() 方法在 case 语句期间永远不会被调用。有任何想法吗?
这是一些示例代码,以及 irb 会话中发生的情况:
class A
def initialize(x)
@x=x #note this isn't even required for this example
end
def ===(other)
puts "in ==="
return true
end
end
irb(main):010:0> a=A.new("hi")
=> #
irb(main):011:0> case a
irb(main):012:1> when "hi" then 1
irb( main):013:1> else 2
irb(main):014:1> end
=> 2
(它从不打印消息,无论如何都应该返回 true)请注意,理想情况下我想做一个
def ===(other)
#puts "in ==="
return @x.===(other)
end
提前致谢。