You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中如何用DRY方式从已有对象复制部分属性到新对象?

优化Ruby对象部分属性复制的冗余代码

你可以通过定义需要复制的属性列表,迭代完成赋值操作来简化代码,既简洁又便于维护,后续增减属性只需修改列表即可:

def set_message_settings_from_existing(existing)
  [:can_message, :current_format, :send_initial_message, :send_alert, :location].each do |attr|
    self.send("#{attr}=", existing.send(attr))
  end
end

如果你的Ruby版本在2.1及以上,推荐用public_send替代send,这样能避免意外调用到对象的私有方法,更安全:

def set_message_settings_from_existing(existing)
  [:can_message, :current_format, :send_initial_message, :send_alert, :location].each do |attr|
    public_send("#{attr}=", existing.public_send(attr))
  end
end

要是后续可能频繁调整需要复制的属性,还可以把属性列表抽成常量,让代码逻辑更清晰:

MESSAGE_SETTINGS_ATTRIBUTES = [:can_message, :current_format, :send_initial_message, :send_alert, :location]

def set_message_settings_from_existing(existing)
  MESSAGE_SETTINGS_ATTRIBUTES.each do |attr|
    public_send("#{attr}=", existing.public_send(attr))
  end
end

内容的提问来源于stack exchange,提问作者ra-11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:55:20