Skip to content

Instantly share code, notes, and snippets.

@equivalent
Last active January 10, 2019 18:34
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 equivalent/fc8cc72fd1e094fd89fc6245eac235e9 to your computer and use it in GitHub Desktop.
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 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 ? :)
@matugm
Copy link

matugm commented Jan 10, 2019

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