Created
August 28, 2012 13:59
-
-
Save undecided/3498233 to your computer and use it in GitHub Desktop.
Another ruby funny that caught me out... Want to guess what these should output?
This file contains 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
"fish" =~ /ish/ | |
"fish" !=~ /ish/ | |
!("fish" =~ /ish/) # equivalent to "fish" !~ /ish/ - thanks @MrJaba and @kerryb! |
The answer, with props to @MrJaba, is that the syntax actually splits up like this:
"fish" != ~/ish/
So it applies the unary one's compliment operator to a regexp before doing an inequality test. The ~ operator, for those who don't know, does this:
~1 #=> -2 - turning binary 0000 0001 into 1111 1110
~42 #=> -43 - turning binary 0010 1010 into 1101 0101
This is undefined for string, and even boolean, but for regex it is defined as nil. No idea why.
So the only way of getting a false with a regex would be:
nil !=~ /anything goes here/
Anything non-nil will always return true, thanks to the !=
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good catch, exactly the same time as Tom! But I'm super-curious as to what !=~ does... it gives a result, just it always seems to be true!