-
-
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 |
defined?(foo) ? nil : foo = "bar"
foo => "bar"
defined?(foo) ? nil : foo = "bar" => is not clean for ruby language
The last solution is better
The last solution relies on instance variable not local one's, therefore is not applicable in many cases (static method i.e.)
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.
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.
foo # NameError: undefined local variable or method `foo' for main:Object
unless defined?(foo)
foo = "bar"
end
foo # => "bar