Class variables

P

Perry Smith

I must have a fundamental misunderstanding of Ruby. I am hoping someone
here can help. This is the essence of what I am doing. I am doing this
inside Ruby On Rails so it may be that Rails is doing something I don't
know about. But here is what I am doing:

class SubClass1 < ParentClass
@@var = "hello1"
end

class SubClass2 < ParentClass
@@var = "hello2"
end

class SubClass3 < ParentClass
@@var = "hello3"
end

class ParentClass
def foo
puts @@var
end
end

i = SubClass1.new
i.foo()

The call to foo and the puts will print out what appears to be a random
value. Sometimes it is "hello1" but other times it is not. It is
always one of the strings, especially when going through Rails and
interacting with the web server, it seems random which string will print
out.

What am I missing here? This seems pretty obvious and straight forward.

Thank you for your help,
pedz
 
P

Phrogz

I must have a fundamental misunderstanding of Ruby. I am hoping someone
here can help. This is the essence of what I am doing. I am doing this
inside Ruby On Rails so it may be that Rails is doing something I don't
know about. But here is what I am doing:

Please search the mailing list archives, and/or read the (free) online
books about it. You will find many, many discussions over how class
variables work when inheritance is involved (hint: they're shared),
and many, many suggestions that in most cases you really want class
instance variables (which are not shared between parent/subclasses).
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top