# Class variables

**URL:** <https://rubytalk.org/t/class-variables/40825>\
**Category:** ruby-talk\
**Created:** [22 September 2007 00:32 UTC](https://rubytalk.org/t/class-variables/40825 "2007-09-22T00:32:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Perry\_Smith](https://avatars.discourse-cdn.com/v4/letter/p/db5fbb/32.png) [@Perry\_Smith](https://rubytalk.org/u/Perry_Smith)\
**Post date:** [22 September 2007 00:32 UTC](https://rubytalk.org/t/class-variables/40825/1 "2007-09-22T00:32:36Z")

</div>

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  
&nbsp;&nbsp;@@var = "hello1"  
end

class SubClass2 \< ParentClass  
&nbsp;&nbsp;@@var = "hello2"  
end

class SubClass3 \< ParentClass  
&nbsp;&nbsp;@@var = "hello3"  
end

class ParentClass  
&nbsp;&nbsp;def foo  
&nbsp;&nbsp;&nbsp;&nbsp;puts @@var  
&nbsp;&nbsp;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

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Gavin\_Kistner3](https://avatars.discourse-cdn.com/v4/letter/g/dfb087/32.png) [@Gavin\_Kistner3](https://rubytalk.org/u/Gavin_Kistner3)\
**Post date:** [22 September 2007 03:10 UTC](https://rubytalk.org/t/class-variables/40825/2 "2007-09-22T03:10:04Z")

</div>

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).

> **···**
>
> On Sep 21, 6:32 pm, Perry Smith \<p...@easesoftware.com\> wrote:
> 
> > 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:
