在 ruby 类的特征类中设置实例默认值



这是我设法实现这一目标的一种方式。

class Test
 class << self
    attr_accessor :stuff
    def thing msg
      @stuff ||= ""
      @stuff += msg
    end
  end
  def initialize
    @stuff = self.class.stuff
    puts @stuff
  end
end
# Is there a better way of accomplishing this?
class AThing < Test
  thing "hello"
  thing "world"
end
AThing.new
# Prints "helloworld"

Ahing中的界面是我想要的最终结果。我真正讨厌的(我觉得一定有更好的完成方式)是@stuff=自我.class的东西。

有没有更好的方法可以使用特征类为自己的所有实例设置默认数据集,同时保持"漂亮"的界面?

我想用这样的代码完成的是有一个类方法,比如add_something向存储在类变量中的数组添加一些东西。

当类被实例化时,它将在其初始化方法中使用此数组来设置该实例的状态。

class Test
  @@stuff = ""
  class << self
    def thing msg
      @@stuff.concat(msg)
    end
  end
  def initialize
    puts @@stuff
  end
end
class AThing < Test
  thing "hello"
  thing "world"
end
AThing.new
# Prints "helloworld"

最新更新