我有一个类,我想在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(主):010:0>一个= A.new(QUOT;喜&QUOT),点击   => #
  IRB(主):011:0>案例一个
  IRB(主):012:1>什么时候“hi”然后1
  IRB(主):013:1>别的2
  IRB(主):014:1>最终结果   => 2个结果

(它从不打印消息,无论如何都应该返回true) 请注意,理想情况下我想做一个

def ===(other)
          #puts "in ==="
          return @x.===(other)
end

提前致谢。

有帮助吗?

解决方案

'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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top