我有一个类,我想在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
Run Code Online (Sandbox Code Playgroud)
irb(main):010:0> a = A.new("hi")
=>#
irb(main):011:0> case a
irb(main):012:1>当"hi"然后是1
irb( main):013:1> else 2
irb(main):014:1> end
=> 2
(它从不打印消息,无论如何应该总是返回true)注意理想情况下我想做一个
def ===(other)
#puts "in ==="
return @x.===(other)
end
Run Code Online (Sandbox Code Playgroud)
提前致谢.
'case'关键字后面的表达式是===表达式的右侧,'when'关键字后面的表达式位于表达式的左侧.因此,被调用的方法是String.===,而不是A.===.
快速逆转比较的方法:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5321 次 |
| 最近记录: |