How do you redefine the ruby ​​case equality operator? (===)

I have a class that I want to compare with strings and characters in a case case, so I thought that I was just overriding the === () method for my class, and everything would be golden. However, my === () method is never called during a case statement. Any ideas?

Here is a sample code, and what happens in an 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 a message and should always return true) Note that ideally I would like to do

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

Thanks in advance.

+5
1

"case" ===, "" . , , , 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
+7

All Articles