module A
a=3D1
@b=3D2
@@c=3D3
$d=3D4
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 # =3D> "bar"
# ... later ...
module Foo # reopening, not defining
old_bar =3D method
bar)
define_method
bar) do
"foo" + old_bar.call
end
end
old_bar # =3D> raises NameError: undefined local variable or method `old_ba=
r'
Foo.bar # =3D> "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 =3D 42
end
module Bar
puts @test
end
# =3D> 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 =3D "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 =3D 42
BAR =3D 43 # =3D> warning: already initialized constant BAR
module FOO
BAR =3D 42
end
puts FOO::BAR # =3D> 42
module
BAR =3D 43
end
# =3D> warning: already initialized constant BAR
Jacob Fugal