你如何覆盖 ruby case 相等运算符?(===) [英] How do you override the ruby case equality operator? (===)
问题描述
我有一个类,我想在 case 语句中与字符串和符号进行比较,所以我认为我只是覆盖了我的类的 ===() 方法,一切都将是黄金.然而,我的 ===() 方法在 case 语句中永远不会被调用.有什么想法吗?
这是一些示例代码,以及在 irb 会话中发生的情况:
A 类定义初始化(x)@x=x #注意这个例子甚至不需要结尾def ===(其他)把在==="返回真结尾结尾
<块引用>
irb(main):010:0> a=A.new("hi")
=> #
irb(main):011:0> case a
irb(main):012:1> 当hi"然后 1
irb(main):013:1> 否则 2
irb(main):014:1> 结束
=> 2
(它从不打印消息,无论如何都应该返回 true)请注意,理想情况下我想做一个
def ===(其他)#puts "in ==="返回@x.===(其他)结尾
提前致谢.
'case' 关键字后的表达式在 === 表达式的右侧,'when' 关键字后的表达式在左侧手边的表情.所以,被调用的方法是 String.===,而不是 A.===.
反转比较的快速方法:
class Revcomp定义初始化(对象)@obj = 对象结尾def ===(其他)其他 === @obj结尾def self.rev(obj)Revcomp.new(obj)结尾结尾课堂测试def ===(其他)把这里"结尾结尾t = 测试.new案例t当 Revcomp.rev("abc")把那里"别的把某处"结尾
I have a class that I want to compare to both strings and symbols in a case statement, so I thought that I just override the ===() method for my class and all would be gold. However my ===() method never gets called during the case statement. Any ideas?
Here is some example code, and what happens in a irb session:
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
(it never prints the message and should always return true anyway) Note that ideally I'd like to do a
def ===(other)
#puts "in ==="
return @x.===(other)
end
Thanks in advance.
The expression after the 'case' keyword is the right hand side of the === expression, and the expression after the 'when' keyword is on the left hand side of the expression. So, the method that is being called is String.===, not A.===.
A quick approach to reversing the comparison:
class Revcomp
def initialize(obj)
@obj = obj
end
def ===(other)
other === @obj
end
def self.rev(obj)
Revcomp.new(obj)
end
end
class Test
def ===(other)
puts "here"
end
end
t = Test.new
case t
when Revcomp.rev("abc")
puts "there"
else
puts "somewhere"
end
这篇关于你如何覆盖 ruby case 相等运算符?(===)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!