Class Level Variables

G

German Monfort

El Lunes, 30 de Abril de 2007 19:15, Gary Wright escribi=F3:
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 Wright

OK, I now understand the difference.

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

I still need to read more and more :D

Thanks Gary
 
G

Gary Wright

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 Wright
 

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
474,241
Messages
2,571,223
Members
47,856
Latest member
mmorais

Latest Threads

Top