本文介绍了Ruby的attr_accessor如何产生类变量或类实例变量而不是实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个带有attr_accessor的类,则默认情况下将创建一个实例变量以及相应的getter和setter.但是,除了创建实例变量之外,还有没有办法让它创建类变量或类实例变量?

If I have a class with an attr_accessor, it defaults to creating an instance variable along with the corresponding getters and setters. But instead of creating an instance variable, is there a way to get it to create a class variable or a class instance variable instead?

推荐答案

像这样:

class TYourClass
  class << self
    attr_accessor :class_instance_variable
  end
end

您可以将其视为打开类的元类(该类本身是实例)并为其添加属性.

You can look at this as opening the metaclass of the class (of which the class itself is an instance) and adding an attribute to it.

attr_accessor是类Class的方法,它将两个方法添加到该类中,一个方法读取实例变量,另一个方法对其进行设置.这是一个可能的实现:

attr_accessor is a method of class Class, it adds two methods to the class, one which reads the instance variable, and other that sets it. Here's a possible implementation:

class Class
  def my_attr_accessor(name)
    define_method name do
      instance_variable_get "@#{name}"
    end
    define_method "#{name}=" do |new_val|
      instance_variable_set "@#{name}", new_val
    end
  end
end

完全未经测试的类属性访问器:

Completely untested class attribute accessor:

class Class
  def class_attr_accessor(name)
    define_method name do
      class_variable_get "@@#{name}"
    end
    define_method "#{name}=" do |new_val|
      class_variable_set "@@#{name}", new_val
    end
  end
end

这篇关于Ruby的attr_accessor如何产生类变量或类实例变量而不是实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:26