Daniel Schierbeck
6/11/2006 9:09:00 AM
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