ruby-on-rails – `@ count`是Ruby中的实例变量还是类变量?

class Counter
   def self.counted_new
      @count = 0 if @count.nil?
      @count += 1
      new
   end

   def self.count
      @count
   end
end

在格式中,@ count看起来像一个实例变量,但当我在“irb”(接口ruby)中加载它并输入四个命令代码时

Counter.counted_new
Counter.count
Counter.counted_new
Counter.count

@count终于成了2!表现得像一个类变量

最佳答案
@count始终是一个实例变量,但如果在该上下文中声明它,它可以是类的实例变量.

在这种情况下,@ count是一个类实例变量.换句话说,通过在类级方法中编写@count,您将为该类分配一个变量.

通过在实例方法中编写@count,您将分配仅在该特定实例中可用的实例变量.

如果使用@@ count声明变量,则会得到一个类变量.

类变量和类实例变量之间的主要区别是类变量保留在继承中.

class Foo
  @@klass = "class level variable"
  @klass_instance = "class instance level variable"
end

class Bar < Foo
end


puts Foo.instance_variables.inspect # => [:@klass_instance]
puts Foo.class_variables.inspect  # => [:@@klass]

puts Foo.instance_variable_get(:@klass_instance)
# => "klass instance level variable"
puts Foo.class_variable_get(:@@klass)
# => "class level variable"

# The class variable is inherited, but the class instance variable is not

puts Bar.instance_variables.inspect # => []
puts Bar.class_variables.inspect  # => [:@@klass]

# The @@klass variable is shared between all classes in the downward inheritance chain
# So for example:
Foo.class_variable_set(:@@klass, "foo")
puts Bar.class_variable_get(:@@klass) # => "foo"

转载注明原文:ruby-on-rails – `@ count`是Ruby中的实例变量还是类变量? - 代码日志