Last active
January 10, 2019 18:34
-
-
Save equivalent/fc8cc72fd1e094fd89fc6245eac235e9 to your computer and use it in GitHub Desktop.
Ruby code brain teaser. Just copy paste to IRB and see for yourself. Question: why did the first example worked ? :)
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
# this Ruby method definiton will get defined successfuly | |
def | |
'magic !' | |
end | |
# but this Ruby method definiton will Fail with syntax error: syntax error, unexpected keyword_end, expecting end-of-input | |
def | |
'magic !' | |
end | |
# Question on you: Why didn't the first example throw syntax error ? :) | |
# Who will figure it out first ? :) |
Answer
1st Definition
The 1st definition has an Unicode character, specifically the character is U+2001.
It looks like an empty space.
Ruby allows creating methods using Unicode characters.
2nd Definition
The 2nd definition uses an empty space (ASCII 32, or 20 in hex).
An empty space is not a valid method name in Ruby.
Conclusion
Because the 1st definition uses an empty-looking character in the Unicode character set Ruby considers this a valid method name, but the 2nd definition uses an actual empty space, which is not valid.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We have winners 🎊 :
(delay of first two answer was like 1 minute so close win :) )
Answer to this question:
First example is defined with different UTF-8 whitespace character . Second example is defined with normal regular space.
There are different "white space" characters in UTF-8 world (e.g. Tab, no-brake spaces etc) defined in UTF-8 char set http://jkorpela.fi/chars/spaces.htm, Ruby supports UTF-8 code. (Ruby since v 1.9 I think)
So if you want to mess around with your college define method like this: