4thSpace 4thSpace - 3 months ago 7
Ruby Question

Why does this instance variable fall out of scope?

Why does

@test
go out of scope in
Aclass
? When
a.print_test
is called, I get an undefined for
@test
.

class Aclass
def print_test
puts "@test from Aclass: " + @test
end
end

a = Aclass.new
#a.print_test

#but still in scope here
puts "After print_test call: " + @test


On a side note, any one know how to get the run code button? I don't see it in the toolbar.

Answer

@var is short hand to access an instance variable on the current instance of a class, or self.

@test = 'what'
puts self
puts self.instance_variable_get :@test

class Aclass
  def print_test
    puts self
    puts self.instance_variable_get :@test
  end
end

a = Aclass.new
a.print_test

So the scope has changed between the main program and the instance of the class.