From: Gary Wright Date: 2010-09-08T03:35:05+09:00 Subject: Re: Dynamic variables in blocks vs constants 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