Skip to content

Instantly share code, notes, and snippets.

@nel
Created September 28, 2011 13:49
Show Gist options
  • Save nel/1247975 to your computer and use it in GitHub Desktop.
Save nel/1247975 to your computer and use it in GitHub Desktop.
foo # NameError: undefined local variable or method `foo' for main:Object
foo = "bar" unless defined?(foo)
foo # => nil
@nicolasva
Copy link

defined?(foo) ? nil : foo = "bar" => is not clean for ruby language

The last solution is better

@nel
Copy link
Author

nel commented Nov 6, 2011

The last solution relies on instance variable not local one's, therefore is not applicable in many cases (static method i.e.)

@anoiaque
Copy link

anoiaque commented Nov 6, 2011

instance variable in class methods is a an class instance variable, so it should work even if its not really beautiful in many cases.

Anyway , my answer was not to give a solution but to show that the behaviour wasn't happen with instance variable.
Im not sure but Ii think its because local variable are defined in scope at parsing (when affected a value) what is not for ivars.

@nel
Copy link
Author

nel commented Nov 6, 2011

Yep, it's ok in the case you want scope wide memoization on that variable. But you are right we are diverging the purpose of the gist/comments was just to expose corner case in ruby language.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment