Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

scope of @var ?

0 views
Skip to first unread message

Une bévue

unread,
Jun 11, 2006, 4:53:28 AM6/11/06
to
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

Daniel Schierbeck

unread,
Jun 11, 2006, 5:08:57 AM6/11/06
to

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

Une bévue

unread,
Jun 11, 2006, 5:09:23 AM6/11/06
to
Une bévue <pere...@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

Une bévue

unread,
Jun 11, 2006, 5:14:23 AM6/11/06
to
Daniel Schierbeck <daniel.s...@gmail.com> wrote:

> This is the correct approach

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

0 new messages