4thSpace
4thSpace

Reputation: 44352

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.

Upvotes: 0

Views: 44

Answers (1)

Matt
Matt

Reputation: 74879

@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.

Upvotes: 2

Related Questions