Given the following example in Ruby 2.0.0:
class Regexp
def self.build
NumRegexp.new("-?[\d_]+")
end
end
class NumRegexp < Regexp
def match(value)
'hi two'
end
def =~(value)
'hi there'
end
end
var_ex = Regexp.build
var_ex =~ '12' # => "hi there" , as expected
'12' =~ var_ex # => nil , why? It was expected "hi there" or "hi two"
According to the documentation of Ruby of the =~
operator for the class String
:
str =~ obj → fixnum or nil
"If obj is a Regexp, use it as a pattern to match against str,and returns the position the match starts, or nil if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~ in Object returns nil."
http://www.ruby-doc.org/core-2.0.0/String.html#method-i-3D-7E
It is a fact that the variable var_ex
is an object of class NumRegexp
, hence, it is not a Regexp
object. Therefore, it should invoke the method obj.=~
passing the string as an argument, as indicated in the documentation and returning "hi there"
.
In another case, maybe as NumRegexp
is a subclass of Regexp
it could be considered a Regexp
type. Then, "If obj is a Regexp use it as a pattern to match against str". It should return "hi two"
in that case.
What is wrong in my reasoning? What do I have to do to achieve the desired functionality?