[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

scope of @var ?

pere.noel

6/11/2006 8:53:00 AM

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 ?
--
une bévue
3 Answers

Daniel Schierbeck

6/11/2006 9:09:00 AM

0

Une bévue wrote:
> 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

pere.noel

6/11/2006 9:09:00 AM

0

Une bévue <pere.noel@laponie.com.invalid> wrote:

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

this trick doesn't make a better job ))
--
une bévue

pere.noel

6/11/2006 9:14:00 AM

0

Daniel Schierbeck <daniel.schierbeck@gmail.com> wrote:

> This is the correct approach

OK thanks, that's clear to me !
--
une bévue