【问题标题】:Difference between the "@" instance variable belonging to the class object and "@@" class variable in Ruby? [duplicate]属于类对象的“@”实例变量和Ruby中的“@@”类变量之间的区别? [复制]
【发布时间】:2014-06-18 21:21:01
【问题描述】:

根据wikibooks...

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

我的问题:

@one 和@@value 有什么区别?
另外,有理由使用@one 吗?

class MyClass
  @one = 1
  @@value = 1

  def initialize()
    @two = 2
  end
end

【问题讨论】:

    标签: ruby


    【解决方案1】:

    @one 是类MyClass 的实例变量,@@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
    

    @two 是类MyClass 的实例的实例变量。

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

    【讨论】:

    • @one@two 有何不同?我知道@two 属于 MyClass 的实例,但我不明白实例变量如何只属于类对象而不属于类的实例。
    • @ayjay 现在清楚了吗?
    • 是的。谢谢你的解释!
    • @ayjay 很高兴为您提供帮助.. :)
    【解决方案2】:

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

    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
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-11
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      相关资源
      最近更新 更多