属于类对象的“@”实例变量和Ruby中的“@@”类变量之间的区别?

根据wikibooks …

  • @one下面属于类对象的实例变量(注意这与类变量不同,不能称为@@one
  • @@value一个类变量 (类似于Java或C ++中的static)。
  • @two 属于 MyClass 实例的实例变量

我的问题:

@one和@@值之间有什么区别?
另外,是否有理由使用@one?

 class MyClass @one = 1 @@value = 1 def initialize() @two = 2 end end 

@oneMyClass类的实例变量, @@value是类变量MyClass 。 由于@one是一个实例变量,它只由MyClass类拥有( 在Ruby类中也是对象 ),不可共享 ,但@@value是一个共享变量

共享变量

 class A @@var = 12 end class B < A def self.meth @@var end end B.meth # => 12 

非共享变量

 class A @var = 12 end class B < A def self.meth @var end end B.meth # => nil 

@twoMyClass类的实例的实例变量。

实例变量是对象的私有属性,因此它们不会共享它。 在Ruby中,类也是对象。 @one你在一个MyClass类中定义,因此它只由定义它的类所拥有。 另一方面,当您使用MyClass.new创建MyClass类的对象时,将创建@two实例变量。 @two只归ob ,其他任何对象都不知道它。

我想到的方式是谁应该持有信息或能够执行任务(因为类方法与实例方法相同)。

 class Person @@people = [] def initialize(name) @name = name @@people << self end def say_hello puts "hello, I am #{@name}" end end # Class variables and methods are things that the collection should know/do bob = Person.new("Bob") # like creating a person Person.class_variable_get(:@@people) # or getting a list of all the people initialized # It doesn't make sense to as bob for a list of people or to create a new person # but it makes sense to ask bob for his name or say hello bob.instance_variable_get(:@name) bob.say_hello 

我希望有所帮助。