Last active
December 21, 2022 17:20
-
-
Save timuruski/c14f4565ae833c00a66a to your computer and use it in GitHub Desktop.
Tip: RegExp implements case equality.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# If you want to check whether a string matches a regular expression, | |
# but not return the match data, you can just use === the case equality operator. | |
# Bad | |
!! ('foobar' =~ /bar/) #=> true | |
!! ('foo' =~ /bar/) #=> false | |
# Good | |
/bar/ === 'foobar' #=> true | |
/bar/ === 'foo' #=> false | |
# This makes sense if you think about it in a case statement and === for RegExp. | |
case 'foobar' | |
when /foo/ | |
"makes sense" | |
end | |
# Implementing === on String to match RegExp is less sensical. | |
case /foo/ | |
when 'foobar' | |
"doesn't make sense" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment