2012-09-08 137 views
2

好了,所以我有這個簡單的類爲什麼我不能在ruby中訪問實例變量?

class Test 
    @var = 99 

    def initialize(var2) 
    @var2 = var2 
    end 

    attr_reader :var, :var2 
end 

> t = Test.new(100) 
=> #<Test:0x007f9b8118ac30 @var2=100> 
> t.var2 
=> 100 
> t.var 
=> nil 

爲什麼是最後t.var語句,返回比零我希望它在班上名列前茅,因爲@var = 99 99返回。也許我對範圍的想法不是100正確的...這個任何想法

回答

9

請參閱代碼中的註釋。

class Test 
    @var = 99 # self is Test class at this point. You're defining 
      # an instance variable on a class instance. 

    def initialize(var2) 
    @var2 = var2 # This is normal instance variable. 
    end 

    attr_reader :var, :var2 
end 

t = Test.new(100) 
t.var # => nil 
t.var2 # => 100 

# don't bother with creating an accessor and get the ivar from Test directly. 
Test.instance_variable_get(:@var) # => 99 
相關問題