Dynamic variables in blocks vs constants

K

Krzysztof Loch

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.
 
G

Gary Wright

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 =3D 3
ruby-1.9.2-p0 ?> 1.times {
ruby-1.9.2-p0 > MyOtherConstant =3D 4
ruby-1.9.2-p0 ?> }
ruby-1.9.2-p0 ?> end
=3D> 1=20
ruby-1.9.2-p0 >=20
ruby-1.9.2-p0 > p MyLibrary.constants
[:MyConstant, :MyOtherConstant]
=3D> [:MyConstant, :MyOtherConstant]=20
ruby-1.9.2-p0 >=20

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 `<main>'
ruby-1.9.2-p0 > Foo =3D 3
=3D> 3=20
ruby-1.9.2-p0 > Object::Foo
=3D> 3=20
ruby-1.9.2-p0 >=20

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

ruby-1.9.2-p0 > Object::pI =3D 3.1415927
=3D> 3.1415927=20
ruby-1.9.2-p0 > PI
=3D> 3.1415927=20
ruby-1.9.2-p0 >=20



Gary=
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top