Ruby:将实例变量添加到对象

如何将一堆实例变量从一个对象添加到另一个对象?

例如,想象您拥有基础机器人的机器人,您可以使用附加组件对其进行自定义.

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

我想重新编写add_attributes方法来简单地迭代每个插件属性,而不是逐个编写它们,因为可能有几十个属性.

一些插件可能有Robot没有的实例变量,我也想将它们添加到Robot.就像在运行中创建实例变量一样?

解决方法

这取决于你所说的“属性”; Ruby没有直接使用该概念,但您可以将实例变量从一个对象复制到另一个对象:

def add_attributes(addon)
  addon.instance_variables.each do |x|
    self.instance_variable_set(addon.instance_variable_get(x))
  end      
end

[编辑]请注意,answer by @HolgerJust也是一个很好的解决方案.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...