2

好的,所以我有这个简单的课程

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语句返回 nil 而我希望它返回 99 因为@var = 99类的顶部。也许我对范围的想法不是 100 正确......关于这个的任何想法

4

1 回答 1

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
于 2012-09-08T18:19:07.837 回答