More class variables. Probably shouldn’t get into this until you’re happy with the general idea from class-var.rb This should demonstrate the way that scoping and so on works with class vars.
Just to say, I’ve not yet found I needed class variables, and as far as I can recall I’ve never seen them used outside examples.
Download this source
class A
@@foo = "class variable foo"
@foo = "class instance variable foo"
# Superfluous, but I was learning at this point ;)
def self.evaluate(txt)
instance_eval txt
end
def self.eval_block(&block)
instance_eval &block
end
end
begin
p A.instance_eval { @@foo }
rescue => e
puts e
end
@@foo = "hi"
p A.instance_eval { [self, @@foo, @foo] }
p A.evaluate("[self, @@foo, @foo]")
p A.eval_block { [self, @@foo, @foo] }
class B
@@foo = "B's class variable foo"
@foo = "B instance foo"
def self.eval_block(&block)
instance_eval &block
end
end
p B.eval_block { [self, @@foo, @foo] }
class C
@@foo = "C's class variable foo"
@foo = "C instance foo"
def self.eval_block(&block)
instance_eval &block
end
end
# N.B. Not C, just B again
p B.eval_block { [self, @@foo, @foo] }
Running this outputs:
uninitialized class variable @@foo in Object
[A, "hi", "class instance variable foo"]
[A, "class variable foo", "class instance variable foo"]
[A, "hi", "class instance variable foo"]
[B, "B's class variable foo", "B instance foo"]
[B, "C's class variable foo", "B instance foo"]

