你可以把工作方式:
irb> class Pair
def initialize(strA,strB)
@strA,@strB = strA,strB
end
def ==(string)
string == @strA || string == @strB
end
def |(other)
Pair.new(self,other)
end
end
#=> nil
irb> class String
def |(other)
Pair.new(self,other)
end
alias old_equals :==
def ==(other)
if other.kind_of? Pair
other == self
else
old_equals other
end
end
end
#=> nil
irb> ("one"|"two") == "one"
#=> true
irb> ("one"|"two") == "two"
#=> true
irb> ("one"|"two") == "three"
#=> false
irb> "one" == ("one"|"two")
#=> true
irb> "three" == ("one"|"two"|"three")
#=> true
但由于这涉及到一个相当低级类的一些猴子补丁,我不会建议依赖于它。其他人会讨厌阅读你的代码。
这个问题没有什么意义可言。字符串“hi”和“ho”的按位或等于“ho”,因此如果s ==“hi”,则您提出的表达式*将返回false *。如果使用不同的字符串,则按位或运算的结果可能更加荒谬。 – molf 2009-07-09 22:08:47