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 ? :)
@equivalent
Copy link
Author

equivalent commented Jan 10, 2019

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:

def my_method 
  "what sorcery is this !?"
end

my_method # => "what sorcery is this !?" 
my_method  # => NameError (undefined local variable or method `my_method' for main:Object)

I'm Joking! Never do this ! If you do you are pure resurrection of evil and there is special place in programming hell for you :rage3: 😄

@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