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

我需要弄清楚如何定义所有者类。我尝试使用调用者,但它返回我的字符串/字符串数组而不是对象、方法或被调用的工作仅适用于相同的方法,“发送者”gem 给了我一个想法,但它是用 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