Last active
July 24, 2017 09:55
-
-
Save AJFaraday/4a03323e3c4a0097d37797f7c57d6903 to your computer and use it in GitHub Desktop.
Unexpected ruby behaviour
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
# found with ruby 2.2.2 (but I think it must have worked on 1.9, too. | |
def meth(arg) | |
argument.is_a?(String) ? 'a' : 'b' | |
end | |
meth('foo') | |
# NameError: undefined local variable or method `argument' for main:Object | |
# This is completely expected, I've never defined `argument`. | |
def meth(arg) | |
argument = argument.is_a?(String) ? 'a' : 'b' | |
end | |
meth('foo') | |
# 'b' | |
# WAT! | |
# It appears that the equals operator defines a local variable, presumably a nil, before executing the if block. |
The presence of argument =
means Ruby allocates a local variable before executing the method body, so the argument
in the right-hand side evals to nil
rather than raising an unknown name error.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Additional information