为什么我不能访问ruby中的实例变量?

时间:2022-08-27 18:08:03

Ok so I have this simple class

我有一个简单的类

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 

Why is the last t.var statement returning nil with I expect it to return 99 because of the @var = 99 on the top of the class. Maybe my idea of scope is not 100 correct...any ideas on this one

为什么最后一个t。var语句返回nil,我希望它返回99,因为在类的顶部有@var = 99。也许我对范围的理解不是100正确……有什么想法吗

1 个解决方案

#1


9  

See comments in the code.

请参阅代码中的注释。

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

#1


9  

See comments in the code.

请参阅代码中的注释。

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