2

これは、私がこれを達成するために管理した 1 つの方法です。

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 です。

「きれいな」インターフェースを維持しながら、固有クラスを使用してそれ自体のすべてのインスタンスのデフォルトのデータセットを設定するより良い方法はありますか?

このようなコードで達成したいことは、クラス変数に格納された配列に何かを追加する add_something などのクラス メソッドを持つことです。

クラスがインスタンス化されると、その初期化メソッドでこの配列を使用して、そのインスタンスの状態を設定します。

4

1 に答える 1

2
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"
于 2014-02-24T07:48:54.387 に答える