Class Level Variables

On Apr 30, 2007, at 1:52 PM, German Monfort wrote:

end
end

I’m confused here.
I was illustrating the fact that C and E don’t share the same @@bar
due to
initialization order and the location of the definitions of C.bar and
E.bar.

If you called D.new.foo you would get 43 because @@foo is shared by
C, D, and E
and was updated to reference 43 in the class block that defined E.

If you called D.new.bar you would get 45 because the call to ‘bar’
would be
implemented by the definition in C where @@bar refers to C’s @@bar.
This is
a good example of how class variables are not relative to self!

Gary W.

El Lunes, 30 de Abril de 2007 19:15, Gary W.
escribió:> >> @@bar # this is C’s @@bar

 @@bar           # this is E's @@bar

end
also has
and was updated to reference 43 in the class block that defined E.

If you called D.new.bar you would get 45 because the call to ‘bar’
would be
implemented by the definition in C where @@bar refers to C’s @@bar.
This is
a good example of how class variables are not relative to self!

Gary W.

OK, I now understand the difference.

Probably I’m too new to programming to understand the full power of
class
variables, and I found this concept a little bit dangerous because you
can
affect the whole behavior of a class by simply changing a class variable
in
any other subclass … so I try not to use class variables for noiw.

I still need to read more and more :smiley:

Thanks Gary

On Apr 30, 2007, at 9:32 PM, German Monfort wrote:

OK, I now understand the difference.

Probably I’m too new to programming to understand the full power of
class
variables, and I found this concept a little bit dangerous because
you can
affect the whole behavior of a class by simply changing a class
variable in
any other subclass … so I try not to use class variables for noiw.

Well Ruby’s class variables are unusual in their semantics, even veteran
programmers get confused by them.

The usual recommendation is to use ‘class instance variables’ when you
want to have state associated with a particular class object (vs. a
class hierarchy.) The easiest way to do that is to create attributes
via the singleton class:

class A
class <<self
attr_accessor :alpha
end
end

class B < A
end

A.alpha = 4
puts A.alpha # 4

puts B.alpha # nil
B.alpha = 5
puts B.alpha # 5

puts A.alpha # 4

In this way you define the accessor once but the state is unique to each
class and to each subclass.

Gary W.