# Very noob question about class variables

**URL:** <https://www.ruby-forum.com/t/very-noob-question-about-class-variables/180388>\
**Category:** Ruby\
**Created:** [December 19, 2009, 6:48am UTC](https://www.ruby-forum.com/t/very-noob-question-about-class-variables/180388 "2009-12-19T06:48:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![angel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/49beb7/32.png) [@angel](https://www.ruby-forum.com/u/angel)\
**Post date:** [December 19, 2009, 6:48am UTC](https://www.ruby-forum.com/t/very-noob-question-about-class-variables/180388/1 "2009-12-19T06:48:28Z")

</div>

Hi…I’m learning rub…I know a bit about Python but I’m interested in  
use rails…I made a little program but this has a little bug too…for  
simplify this I dont post the program but I post a example

if I declare  
var=‘hi’

def greeting  
puts var  
end

greeting()  
greting

Do I need declare this like class variable necessarily?..inside my def  
ruby can’t see outside?..

ok…I declare this like a class variable…Now…I need a counter like  
this

i=0

loop {  
i+=1  
puts ‘hi again’

if i\>100000: break end

}

why in this block I can see the outside value for i and inside the def  
block I can’t??

I should not use “standart” variables like variable instead use  
@@variabl??

Please explain me this…and sorry for my poor english…I’m italian

---

<div class="post-metadata">

**Author:** ![angel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/49beb7/32.png) [@angel](https://www.ruby-forum.com/u/angel)\
**Post date:** [December 19, 2009, 7:19am UTC](https://www.ruby-forum.com/t/very-noob-question-about-class-variables/180388/2 "2009-12-19T07:19:00Z")

</div>

On Dec 18, 9:48 pm, Angel M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I should not use “standart” variables like variable instead use  
> @@variabl??
> 
> ## Please explain me this…and sorry for my poor english…I’m italian
> 
> Posted viahttp://www.ruby-forum.com/.

Class variables are for use like this:

Class Supah  
def setVar(val)  
@@var = val  
end

def printVar  
puts @@var  
end  
end

a = Supah.new  
a.setVar ‘hi’

b = Supah.new  
b.printVar

=\> “hi”

Class variables are simply variables that you can access from any  
instance of the class.  
To get a variable inside a def, you can pass it in like a parameter,  
or you can use a global variable, a var prefixed by $.  
In ruby, variables declared outside a function are not part of that  
functions scope.  
Hope this helps.
