1

在 Java 中,我可以声明一个类的公共成员,但在 Ruby 中似乎无法做到这一点。

class Person
  @a = 1

  def hello()
    puts(@a)
  end
end

p = Person.new
p.hello()  
#nil

为什么是输出nil而不是1

4

1 回答 1

1

因为实例变量 @a 没有为 instance 初始化pr

class Person
@a = 1
  def hello()
    puts(@a)
  end
end

pr = Person.new
pr.instance_variable_get(:@a) # => nil

现在见下图:-

class Person
  def initialize(a)
    @a=a
  end
  def hello()
    puts(@a)
  end
end

pr = Person.new(1)
pr.instance_variables # => [:@a]
Person.instance_variables # => []
pr.instance_variable_get(:@a) # => 1
pr.hello # => 1

Instance variables

实例变量的名称以 @ 开头,其作用域仅限于 self 所指的任何对象。两个不同的对象,即使它们属于同一个类,也允许它们的实例变量具有不同的值。从对象外部,实例变量不能被更改甚至观察(即,ruby 的实例变量永远不会公开),除非通过程序员明确提供的任何方法。与全局变量一样,实例变量在初始化之前都具有 nil 值。


现在看这里:-

class Person
@a = 1
  def self.hello()
    puts(@a)
  end
end
Person.hello # => 1
Person.instance_variables # => [:@a]
Person.new.instance_variables # => []

所以在这个例子中,@a 是对象的实例变量Person,而不是 . 的实例。Person非常好的提示在这里 - Class Level Instance Variables

于 2013-08-29T18:17:36.970 回答