class variable weirdness

B

Bob Sidebotham

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
 
C

Christoph Neubauer

Bob Sidebotham said:
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:
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
 
R

Robert Klemme

Bob Sidebotham said:
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
 

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,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top