【问题标题】:Setting instance defaults in the eigenclass of ruby classes在 ruby​​ 类的 eigenclass 中设置实例默认值
【发布时间】:2014-03-25 17:50:44
【问题描述】:

这是我设法做到这一点的一种方法。

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"

AThing 中的界面是我想要的最终结果。我真正讨厌(而且我觉得必须有更好的方法)是@stuff = self.class.stuff。

有没有更好的方法来使用 eigenclass 为自身的所有实例设置默认数据集,同时保持“漂亮”的界面?

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

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

【问题讨论】:

  • @stuff = self.class.stuff 有什么不好?类变量会起作用吗?
  • @stuff = @@stuff?我只是觉得它很笨拙。虽然它会对普通用户隐藏。我也希望它不要成为公共界面的一部分
  • 是的。这就是我的意思。然后,您不需要在 eigenclass 中执行此操作。
  • 这很有意义。我一定是真的累了。一如既往地感谢。你能发布一个我可以标记的答案吗?

标签: ruby metaprogramming instantiation eigenclass


【解决方案1】:
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"

【讨论】:

    猜你喜欢
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2014-09-03
    • 2021-11-22
    • 1970-01-01
    • 2016-01-06
    相关资源
    最近更新 更多