2016-08-25 4 views
0

Warum geht @test in Aclass aus dem Geltungsbereich? Wenn a.print_test aufgerufen wird, bekomme ich ein undefined für @test.Warum fällt diese Instanzvariable nicht in den Geltungsbereich?

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 

Auf einer Randnotiz, weiß jemand, wie man den Laufcodeknopf erhält? Ich sehe es nicht in der Symbolleiste.

Antwort

2

@var ist eine kurze Hand, um auf eine Instanzvariable für die aktuelle Instanz einer Klasse oder self zuzugreifen.

@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 

Also der Bereich hat sich zwischen dem Hauptprogramm und der Instanz der Klasse geändert.

+0

Das erste 'puts self' ist' main'. Die zweite ist die 'Klasse'. Was ist "hauptsächlich"? – 4thSpace

+2

Das ist eine gute Frage! Nun, wenn es nur eine Website gäbe, auf der man Fragen über die Programmierung stellen könnte (http://stackoverflow.com/q/917811/2988)? –

Verwandte Themen