Ruby:将实例变量添加到对象
发布时间:2020-12-17 01:46:27 所属栏目:百科 来源:网络整理
导读:如何将一堆实例变量从一个对象添加到另一个对象? 例如,想象您拥有基础机器人的机器人,您可以使用附加组件对其进行自定义. class Robot def initialize @name = "simple robot" @power = nil #no power @speed = nil # more attributes end def add_attribut
如何将一堆实例变量从一个对象添加到另一个对象?
例如,想象您拥有基础机器人的机器人,您可以使用附加组件对其进行自定义. 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也是一个很好的解决方案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |