So recently I was looking for a way to do a comparison on a String
with
either another String or a Regexp
. Looking online didn't yield much help,
most discussions on equality focused on ==
, eql?
, equal?
. None of
which would satisfy the requirement. So I was left with this code:
def matches(compare_with)
if compare_with.is_a?(Regexp)
@data_string =~ compare_with
else
@data_string == compare_with
end
end
Thanks to Twitter, specifically @JEG2 who completely
rocks, he pointed me at ===
. All of the docs on ===
say it is the case
statement operator. In fact the
String API
doesn't even mention it. Looking at the
Regexp API it
notes it as a synonym for Regexp#=~
. The thing to remember is with case
:
case thing
when other_thing
The comparison are done with the when
expression as the lvalue. So really,
the above case
statement is the same as other_thing === thing
.
This means our matches
method can be rewritten as:
def matches(compare_with)
compare_with === @data_string
end
This also means it's possible to be more flexible on the match:
# @data_string = "coding for fun"
matches "oding" # false
matches "coding for fun" # true
matches /oding/ # true
matches String # true
So the next time you're thinking of writing some code that needs to
change based on class or how it compares with something else, think
if a case
statement applies. If it does, see if ===
works instead.