Overriding =~ method on a String subclass generates inconsistency Overriding =~ method on a String subclass generates inconsistency ruby ruby

Overriding =~ method on a String subclass generates inconsistency


In the source for the String#=~ method, Ruby handles the special case where the argument is of a built-in Regexp type used by the parser, which is the case when we write s =~ /abc/.

The rb_reg_match method can be found as being the Regexp#=~ method.

Thus, if you really want this behavior you can monkey patch the Regexp class to accept objects of MyString for the =~ operator, but that might go wrong very, very easily.

Another approach would be composition. You can either include the Forwardable module or go with plain old method_missing. Here's an example:

class MyString  attr_reader :string  def initialize(str)    @string = str  end  def method_missing(*args)    string.public_send(*args)  end  def =~(obj)    "Overriden"  endends = MyString.new "abc"s =~ /abc/              # => "Overriden"s =~ Regexp.new("abc")  # => "Overriden"