Dynamic variables in blocks vs constants

Hi, I know that dynamic variables created in block it is not accessible
from outside of that block but I noticed that dynamic constants can be
accessed and I want to know why it is so.

Sorry for my bad english. For better understanding of my problem I’m
attaching code below.

%w[magic MAGIC].each do |x|
eval <<-RUBY
#{x}_dynamic = 1
RUBY
end

And now you can try…

magic_dynamic
MAGIC_dynamic

You can observe it using 1.9 version of ruby.

On Sep 7, 2010, at 1:26 PM, Krzysztof Loch wrote:

Hi, I know that dynamic variables created in block it is not accessible
from outside of that block but I noticed that dynamic constants can be
accessed and I want to know why it is so.

Because constants are always defined in reference to a module and not
in reference to the execution stack/context:

$ irb
ruby-1.9.2-p0 > module MyLibrary
ruby-1.9.2-p0 ?> MyConstant = 3
ruby-1.9.2-p0 ?> 1.times {
ruby-1.9.2-p0 > MyOtherConstant = 4
ruby-1.9.2-p0 ?> }
ruby-1.9.2-p0 ?> end
=> 1
ruby-1.9.2-p0 >
ruby-1.9.2-p0 > p MyLibrary.constants
[:MyConstant, :MyOtherConstant]
=> [:MyConstant, :MyOtherConstant]
ruby-1.9.2-p0 >

If there is no explicit module in scope then Ruby tucks constants
away in the class Object (classes are also modules in Ruby’s object
model)

$ irb
ruby-1.9.2-p0 > Object::Foo
NameError: uninitialized constant Foo
from (irb):1
from irb:17:in `’
ruby-1.9.2-p0 > Foo = 3
=> 3
ruby-1.9.2-p0 > Object::Foo
=> 3
ruby-1.9.2-p0 >

Constants defined in Object are also accessible via at Ruby’s top level
scope:

ruby-1.9.2-p0 > Object::PI = 3.1415927
=> 3.1415927
ruby-1.9.2-p0 > PI
=> 3.1415927
ruby-1.9.2-p0 >

Gary

Thank you Gary for clarification.

Best regards!

Gary W. wrote:


Gary