Bechma
Bechma

Reputation: 517

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.

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.

Upvotes: 0

Views: 243

Answers (2)

sig
sig

Reputation: 392

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')

Upvotes: 0

spickermann
spickermann

Reputation: 106972

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.

But you can change the initalize method and the super call in the subclass to make it work:

Change 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:

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

Upvotes: 1

Related Questions