very noob question about class variables

A

Angel Marques

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
 
P

Philliam Auriemma

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

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.
 

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,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top