Difference between the “@” instance variable belonging to the class object and “@@” class variable in Ruby?
本问题已经有最佳答案,请猛点这里访问。
根据维基书籍…
- 下面的
@one 是一个属于类对象的实例变量(注意这与类变量不同,不能称为@@one ) - EDCOX1 2是一个类变量(类似于Java或C++中的静态)。
@two 是属于myclass实例的实例变量。
我的问题:
@one和@value有什么区别?另外,是否有理由使用@one?
1 2 3 4 5 6 7 8 | class MyClass @one = 1 @@value = 1 def initialize() @two = 2 end end |
共享变量
1 2 3 4 5 6 7 8 9 10 11 | class A @@var = 12 end class B < A def self.meth @@var end end B.meth # => 12 |
非共享变量
1 2 3 4 5 6 7 8 9 10 11 | class A @var = 12 end class B < A def self.meth @var end end B.meth # => nil |
实例变量是对象的私有属性,因此它们不会共享它。在Ruby类中也是对象。
我认为应该由谁来保存信息或者能够完成任务(因为类方法和实例方法是一样的)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |
希望有帮助。