0

特定のメソッド/クラスの所有者を他のクラスから確認する方法を知りたいです。

例えば:

class Value
  attr_accessor :money
  def initialize
    @money = 0.0
  end
  def get_money
    return self.money
  end
  def transfer_money(target, amount)
    self.money -= amount
    target.money += amount
  end
end

class Nation
  attr_accessor :value
  def initialize
    @value = Value.new 
  end
end

class Nation_A < Nation
  def initialize
    super
  end
  def pay_tribute_to_decendant_country
    value.transfer_money(Nation_B.value, 500)
  end
end

class Nation_B < Nation
  def initialize
    super
  end
  def pay_tribute_to_decendant_country
    value.transfer_money(Nation_C.value, 200)
  end
end

class Nation_C < Nation
  def initialize
    super
  end
  def pay_tribute_to_decendant_country
    value.transfer_money(Nation_A.value, 300)
  end
end

ええ、子孫がどのように輪になっていくのか意味がありませんが、異なるサブクラスには異なる引数があるという考えを実装したいと思います。

リストはかなり長いです (少なくとも 40 個はすでにインストールされており、はるかに複雑な子孫ブランチと、Value クラスから transfer_money を呼び出すメソッドが多数あります)。次に、構造に実装するアイデアがあります。通貨を追加したいのですが、すべての transfer_money メソッド呼び出しをオーバーライドすることは、私にとって途方もない作業です。したがって、呼び出しを生成するハッシュ テーブルを作成します。

class Nation
  def self.get_descendants
    ObjectSpace.each_object(Class).select { |klass| klass < self }
  end
end

module Additional_Value

  currency_table = {}

  min = 50
  max = 100

  def self.range (min, max)
    rand * (max-min) + min
  end

  Nation.get_descendants.each do |derived_classes|
      currency_table[derived_classes] == self.range min, max
  end

end

class Value
  attr_accessor :currency
  def initialize
    @money = 0
    @currency = Additional_Value::currency_table
  end
  def transfer_money(target, amount)
    self.money -= amount
    amount = amount * @currency[self.class.owner] / @currency[target.class.owner]
    target.money += amount
  end
end

所有者クラスを定義する方法を理解する必要があります。呼び出し元を使用してみましたが、オブジェクト、メソッド、または呼び出し元の代わりに文字列/文字列の配列が返され、同じメソッドに対してのみ機能します。「送信者」の宝石はアイデアを与えてくれますが、Cで書かれており、使用する必要があります私の事情によるデフォルトのライブラリ。

大変感謝しています。

編集:

問題をより短い方法で書き直します。

class Slave
  def who_is_the_owner_of_me
    return self.class.owner unless self.class.owner.nil?
  end
end

class Test
  attr_accessor :testing
  def initialize
    @testing = Slave.new
  end
end

class Test2 < Test1
end

a = Test.new
b = Test2.new
c = Slave.new
a.testing.who_is_the_owner_of_me  #=> Test
b.testing.who_is_the_owner_of_me  #=> Test2
c.who_is_the_owner_of_me          #=> main
4

0 に答える 0