How can I add a bunch of instance variables from one object to another?
For example, imagine robots where you have the base robot and you can customize it with add-ons.
class Robot
   def initialize
      @name = "simple robot"
      @power = nil #no power
      @speed = nil
      # more attributes
   end
   def add_attributes(addon)
      @power = addon.power
      @speed = addon.speed
      #the rest of the attributes that addon has
   end
end
I would like to re-write the add_attributes method to simply iterate over each of the addon's attributes instead of writing them all one by one, cause there could be dozens of attributes.
Some addons may have instance variables that Robot doesn't have, and I would also like to add them to Robot. Like creating instance variables on the fly?
It depends on what you mean by "attribute"; Ruby doesn't have that concept directly but you could copy instance variables from one object to another as such:
def add_attributes(addon)
  addon.instance_variables.each do |x|
    self.instance_variable_set(addon.instance_variable_get(x))
  end      
end
[Edit] Note that the answer by @HolgerJust is also a good solution.
You could get rid of the instance variables and use a single hash instead. This has the advantage of a free enumerator and a clean interface to access all the features a robot has from one convenient place.
It also avoids having to mess with an instances internal variables. They are typically intended to be internal and are used for a vast amount of stuff. If you want to expose functionality, you should do it with a public method. Messing with internal state is at least bad design and will most probably lead to much grief later on. Generally, it's best to avoid meta-programming wherever possible.
class Robot
  attr_reader :features
  def initialize
    @features = {}
    @features[:name] = "simple robot"
    @features[:power] = nil #no power
    @features[:speed] = nil
  end
  def add_attributes(addon)
    @features.merge! addon.features
  end
end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With