scope of @var ?

U

Une bévue

i have a variable saying @var defined within a class "Controller" :

def initialize
...
@var=""
...
prefsSetUp
...
end


i'm using this var in 3 different methods :

def prefsSetUp
...
varSetUp
p @var # => print out OK i get "var_is_defined_right_now"
...
end

def varSetUp
@var="var_is_defined_right_now"
end

def useVar
p @var # => print out NOT OK i get ""
end

does that means the scope of @var is only defined in prefsSetUp where i
do varSetUp even if prefsSetUp is called from Controller#initialize ???

better could be to call varSetUp from Controller#initialize too ?
 
D

Daniel Schierbeck

Une said:
i have a variable saying @var defined within a class "Controller" :

def initialize
...
@var=""
...
prefsSetUp
...
end


i'm using this var in 3 different methods :

def prefsSetUp
...
varSetUp
p @var # => print out OK i get "var_is_defined_right_now"
...
end

def varSetUp
@var="var_is_defined_right_now"
end

def useVar
p @var # => print out NOT OK i get ""
end

does that means the scope of @var is only defined in prefsSetUp where i
do varSetUp even if prefsSetUp is called from Controller#initialize ???

better could be to call varSetUp from Controller#initialize too ?

An instance variable exists the moment you refer to it -- but its value
is nil. If you haven't called #varSetUp (or #var_set_up, which is more
Rubyish,) then @var is nil, which will be printed out as an empty
string. This is the correct approach:

class Test
def initialize
@var = "var is defined"
end

def print_var
p @var
end
end


Cheers,
Daniel
 

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

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,139
Latest member
JamaalCald
Top