如何将超类复制到Ruby

时间:2016-12-06 20:42:45

标签: ruby copy-constructor

我在复制这两个类时遇到问题:

module NapakalakiGame
  class Player

  def initialize(name, level)
    @name = name
    @level = level
    @treasures = Array.new
    @quests = Array.new
  end
...
end

我想在这里复制上述课程的一个实例:

module NapakalakiGame
  class CultistPlayer < Player

  def initialize(player, cultist)
    super
    @my_cultist_card = cultist
  end
...
end

我需要将玩家变成一个邪教徒,所以我需要复制他拥有的所有属性。 CultistPlayer的构造函数接收想要被转换的玩家和一张邪教卡。

例如,如果我有一个名叫约翰的玩家有30级,5种宝藏和20个已完成的任务,当他成为邪教时,我需要保留它。

2 个答案:

答案 0 :(得分:1)

你不能这样做,因为你的Player#new方法不接受相同类型的参数,并且它不接受玩家作为参数。

但您可以更改子类中的initalize方法和super调用以使其正常工作:

更改player.rb

attr_reader :name, :level, :treasures, :quests # if you don't have getter methods

def initialize(name, level, treasures = nil, quests = nil)
  @name      = name
  @level     = level
  @treasures = treasures || []
  @quests    = quests || []
end

cultist_player.rb

def initialize(player, cultist)
  super(player.name, player.level, player.treasures, player.quests)
  @my_cultist_card = cultist
end

答案 1 :(得分:0)

我不确定&#34;转换&#34;是最好的建筑方法。但如果你真的需要它,你可以尝试这样写:

class CultistPlayer < Player
 def initialize(player, cultist)
   copy_variables(player)
   @my_cultist_card = cultist
 end

 def copy_variables player
   player.instance_variables.each do |name|
     instance_variable_set(name, player.instance_variable_get(name))
   end
 end
end

#usage:
simple_player = Player.new('Ben', 10)
cultist = CultistPlayer.new(simple_player, 'some cultist card')