0

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.

4thSpace
  • 43,672
  • 97
  • 296
  • 475

1 Answers1

2

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

Matt
  • 68,711
  • 7
  • 155
  • 158
  • The first `puts self` is `main`. The second is the `class`. What is `main`? – 4thSpace Aug 25 '16 at 04:54
  • 2
    That is a good question! Now, if only there were some website where one could [ask questions about programming](http://stackoverflow.com/q/917811/2988)? – Jörg W Mittag Aug 25 '16 at 06:43