Class variable weirdness

This program runs, and prints "Foo" (as expected).

module Mod
   def get
     @@var
   end
   @@var = "Mod" # Removing this causes error
end

class Foo
   include Mod
   @@var = "Foo"
end

puts Foo.new.get

···

-------------

But if I remove the commented line, above, then I get:

   uninitialized class variable @@var in Mod (NameError)

This is with ruby 1.8.2 (2004-09-10) [i686-linux]

Is this a bug, feature, or am I just missing something?

Thanks,
Bob Sidebotham

"Bob Sidebotham" <bob@windsong.bc.ca> wrote in message
news:F7v2d.432470$M95.325276@pd7tw1no...

But if I remove the commented line, above, then I get:

   uninitialized class variable @@var in Mod (NameError)

This is with ruby 1.8.2 (2004-09-10) [i686-linux]

Is this a bug, feature, or am I just missing something?

Thanks,
Bob Sidebotham

Hi Bob !

It's the same behaviour on ruby 1.6.8 (2002-12-24) [i586-mswin32]

"Programming Ruby, HTML Help edition (v0.3a)" says about Class Variables:

Unlike global and instance variables, class variables must be initialized

before they are used.
Often this initialization is just a simple assignment in the body of the
class definition. <<

As I understand Ruby and compiling/parsing techniques the error message
says,
that @@var is not initialized --> within the scope of Mod.

As Mod could be included 'anywhere and anyhow' it's the one and only scope
where it is possible in common to check/grant variable initialization.

Kind Regards,
Chris

"Bob Sidebotham" <bob@windsong.bc.ca> schrieb im Newsbeitrag
news:F7v2d.432470$M95.325276@pd7tw1no...

This program runs, and prints "Foo" (as expected).

module Mod
   def get
     @@var
   end
   @@var = "Mod" # Removing this causes error
end

class Foo
   include Mod
   @@var = "Foo"
end

puts Foo.new.get

-------------

But if I remove the commented line, above, then I get:

   uninitialized class variable @@var in Mod (NameError)

This is with ruby 1.8.2 (2004-09-10) [i686-linux]

Is this a bug, feature, or am I just missing something?

It's a speciality of class variables: they are visible in the class that
defines them and all sub classes. So, if you remove the assignment in
Mod, it's defined in Foo and thus #get can't see it. I know that sounds
wired but it's the way it is. Personally I don't class variables and
that's why I try to avoid them if possible.

Kind regards

    robert