Skip to content

Instantly share code, notes, and snippets.

@AJFaraday
Last active July 24, 2017 09:55
Show Gist options
  • Save AJFaraday/4a03323e3c4a0097d37797f7c57d6903 to your computer and use it in GitHub Desktop.
Save AJFaraday/4a03323e3c4a0097d37797f7c57d6903 to your computer and use it in GitHub Desktop.
Unexpected ruby behaviour
# 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.
@AJFaraday
Copy link
Author

Additional information

a.class
# NameError: undefined local variable or method `a' for main:Object
b = b.class
# => NilClass

@jcoglan
Copy link

jcoglan commented Jul 24, 2017

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