Skip to content

Instantly share code, notes, and snippets.

@gongo
Last active August 29, 2015 14:15
Show Gist options
  • Save gongo/ab19c995f58b55a930ba to your computer and use it in GitHub Desktop.
Save gongo/ab19c995f58b55a930ba to your computer and use it in GitHub Desktop.
`foo` redefined as local variable. Why?
def foo
12
end
p '----------'
p "foo is #{defined?(foo)}"
p "bar is #{defined?(bar)}"
p '----------'
if defined?(bar)
p "In `if` block"
foo = bar
end
p "foo is #{defined?(foo)}"
p "bar is #{defined?(bar)}"
p '----------'
# "----------"
# "foo is method"
# "bar is "
# "----------"
# "foo is local-variable"
# "bar is "
# "----------"
@gongo
Copy link
Author

gongo commented Feb 13, 2015

http://docs.ruby-lang.org/ja/2.1.0/doc/spec=2fdef.html#defined

defined? a = 1
p a # => nil

"assignment" を返します。実際に代入は行いませんがローカル変数は定義されます。 

ここらへんと関わりあるんだろうか…

@gongo
Copy link
Author

gongo commented Feb 14, 2015

http://docs.ruby-lang.org/ja/2.2.0/doc/spec=2fvariables.html#local

宣言は、例え実行されなくても宣言とみなされます。

ということなので foo = bar 実行されなくとも、foo の宣言 が有効であるため、とのこと。

Thanks!!

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