Skip to content

Instantly share code, notes, and snippets.

@undecided
Created August 28, 2012 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save undecided/3498233 to your computer and use it in GitHub Desktop.
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?
"fish" =~ /ish/
"fish" !=~ /ish/
!("fish" =~ /ish/) # equivalent to "fish" !~ /ish/ - thanks @MrJaba and @kerryb!
@undecided
Copy link
Author

Note: If anyone has a link that explains what line 3 is doing, I would appreciate it. I'm sure I once knew, but it certainly is not intuitive.

@undecided
Copy link
Author

(sorry, meant to say second example, which happens to have the line number 3 - just to avoid more confuddlementz)

@kerryb
Copy link

kerryb commented Aug 28, 2012

Aren't you looking for "fish" !~ /ish/ ? I'm not sure what !=~ does.

@undecided
Copy link
Author

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!

@undecided
Copy link
Author

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