[Solved] What is the meaning of operator ==~ in Ruby? [duplicate]


The unary ~ operator has higher precedence than == or =~ so this:

string ==~ /^ABC/

is just a confusing way of writing:

string == (~/^ABC/)

But what does Regexp#~ do? The fine manual says:

~ rxp → integer or nil
Match—Matches rxp against the contents of $_. Equivalent to rxp =~ $_.

and $_ is “The last input line of string by gets or readline.” That gives us:

string == (/^ABC/ =~ $_)

and that doesn’t make any sense at all because the right hand side will be a number or nil and the left hand side is, presumably, a string. The condition will only be true if string.nil? and the regex match fails but there are better ways to doing that.

I think you have two problems:

  1. ==~ is a typo that should probably be =~.
  2. Your test suite has holes, possibly one hole that the entire code base fits in.

See also What is the !=~ comparison operator in ruby? for a similar question.

1

solved What is the meaning of operator ==~ in Ruby? [duplicate]