[英]How to copy the super class into the inherited class in Ruby
I have a problem copying these two classes: 复制这两个类时遇到问题:
module NapakalakiGame
class Player
def initialize(name, level)
@name = name
@level = level
@treasures = Array.new
@quests = Array.new
end
...
end
And I want to copy an instance of the above class here: 我想在这里复制上述类的一个实例:
module NapakalakiGame
class CultistPlayer < Player
def initialize(player, cultist)
super
@my_cultist_card = cultist
end
...
end
I need to transform the Player into a cultist, so I need to copy all the attributes he has. 我需要将播放器转变为崇拜者,因此我需要复制他拥有的所有属性。 The constructor of the CultistPlayer receives the Player who wants to be transformed and one cultist card. CultistPlayer的构造函数会收到要转换的Player和一张cultist卡。
For example, if I have a Player named John that has level 30, 5 kinds of treasures and 20 completed quests, when he becomes a cultist I need to keep it all. 例如,如果我有一个叫John的玩家,拥有30级,5种宝藏和20个完成的任务,当他成为信奉者时,我需要保留所有内容。
You cannot do it that way, because your Player#new
method doesn't accept the same kind arguments and it doesn't accept a player as argument. 您不能那样做,因为您的Player#new
方法不接受相同类型的参数,也不接受玩家作为参数。
But you can change the initalize
method and the super
call in the subclass to make it work: 但是您可以更改子类中的initalize
方法和super
调用以使其起作用:
Change player.rb
: 更改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
and cultist_player.rb
: 和cultist_player.rb
:
def initialize(player, cultist)
super(player.name, player.level, player.treasures, player.quests)
@my_cultist_card = cultist
end
I'm not sure that "transform" is the best architectural approach. 我不确定“转换”是最好的架构方法。 But if you really need it you can try to write like this: 但是,如果您确实需要它,可以尝试这样写:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.