From: Jacob Fugal Date: 2005-12-17T07:50:31+09:00 Subject: Re: Math::PI? On 12/16/05, Daniel Sch�le wrote: > module A > a=1 > @b=2 > @@c=3 > $d=4 > def e;5;end > def A.f;6;end > end > > A::f is the same as A.f > $d is immediatly accessable > A::e, A.e accessable after include A > > what is about a,b and c? $d is immediately available since the $ prefix makes it global. 'a' is a normal variable with local scope. The scope is the module definition. So once you close the method definition the variable goes away. It's still tied in the environment of any closures that referenced it while it was "alive", however. This is useful for instance in metaprogramming: module Foo def bar "bar" end extend self end Foo.bar # => "bar" # ... later ... module Foo # reopening, not defining old_bar = method(:bar) define_method(:bar) do "foo" + old_bar.call end end old_bar # => raises NameError: undefined local variable or method `old_bar' Foo.bar # => "foobar" @b is an instance variable -- specifically, an instance variable on the *current self* where it is used. In this case, that means it's an instance variable on the Module object. So, if you reopen the module and access @b, it will retain the value: module Bar @test = 42 end module Bar puts @test end # => 42 @@c is a class variable -- normally, a class variable on the class of the current self. One would think that since the class of the Module object defined is Module, all Modules will share class variables: module A @@class_var = "xyzzy" end module B puts @@class_var end However, try the above and you'll get "uninitialized class variable @@class_var in B". But if you reopen A, @@class_var is still there. I, not knowing more, can only assume that ruby treats class variables special and uses self as the container -- rather than self.class -- when self is a Class or Module. What's the difference between @b and @@c at the class/module scope then? As far as I can tell, none -- except confusion. > How can I put a constant in the module? Same as usual: BAR = 42 BAR = 43 # => warning: already initialized constant BAR module FOO BAR = 42 end puts FOO::BAR # => 42 module BAR = 43 end # => warning: already initialized constant BAR Jacob Fugal