I had mostly been using === for matching values to patterns in Ruby. Recently, I discovered that the language also supports the =~ operator for regular expressions.
The Ruby Documentation defines === as "case equality" and =~ as "pattern match".
Case Equality – For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.
Pattern Match—Overridden by descendants (notably Regexp and String) to provide meaningful pattern-match semantics.
By experimentation, I find that === works for regular expressions, class names, literal values, and even ranges, while =~ only seems to return useful values for regular expressions. My question is: why would I ever use =~? It seems like === supports everything =~ does and then some. Is there something I'm missing here that =~ is intended to do differently?
Firstly, =~ is symmetric:
'string' =~ /regex/
And
/regex/ =~ 'string'
Both work.
Secondly as you noted, === works with other classes. If you want to match strings, you should be using the operator for... matching. It is called case operator for a reason - case uses it internally.
case foo
when bar then x
when baz then y
else z
end
Is the same as:
if bar === foo
x
elsif baz === foo
y
else
z
end
Explicitly using === is considered unidiomatic.
str = "Something is amiss."
r = /me/
r === str #=> true
str =~ r #=> 2
What if you want to know if there's a match and if so, where it begins?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With