如何将一堆实例变量从一个对象添加到另一个对象?
例如,想象您拥有基础机器人的机器人,您可以使用附加组件对其进行自定义.
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
Run Code Online (Sandbox Code Playgroud)
[编辑]请注意@HolgerJust的答案也是一个很好的解决方案.
您可以删除实例变量并使用单个哈希.这具有免费枚举器和干净界面的优点,可以从一个方便的位置访问机器人的所有功能.
它还避免了必须混淆实例内部变量.它们通常用于内部,并用于大量的东西.如果要公开功能,则应使用公共方法.与内部状态混淆至少是糟糕的设计,很可能会导致后来的悲痛.通常,最好尽可能避免元编程.
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
Run Code Online (Sandbox Code Playgroud)