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

Ruby使用map重构嵌套数组对象时重复输出问题求助

Ruby哈希结构转换问题:重复对象与键名丢失修复

问题背景

需要将response中categorisedFeatures下每个对象的historical数组内的usageByMonth哈希结构,转换为{month: k, value: v}格式的对象数组。编写的代码运行后出现两个问题:

  1. 同一个historical对象被重复输出多次
  2. 直接返回处理后的对象会丢失PLATFORM这类顶级键名

原始代码

categorisedFeatures = response[:categorisedFeatures].map do |feature|
   newHistorical = (feature.dig(1, :historical)).map do |historical|
     usageByMonthRefactor = historical.dig(:usageByMonth)&.map { |(k, v)| { 'month': k, 'value': v } }
           newEntry = historical.merge({
               usageByMonth: usageByMonthRefactor
            })
     end
    newFeature = feature.dig(1).merge ({
      historical: newHistorical
    }) 
 feature&.map { |(k,v)| k=k , v=newFeature}

 end

问题分析

  1. 重复对象原因:response[:categorisedFeatures]是哈希,调用map会返回由[键, 值]组成的数组。最后一行feature&.map { |(k,v)| k=k , v=newFeature}会把每个[键, 值]数组的两个元素都映射成[键, newFeature],导致每个feature生成两份重复数据。
  2. 键名丢失原因:直接返回newFeature时,只保留了哈希的value部分,丢弃了原始的顶级键(如PLATFORM、CMS)。

修复后的代码

categorisedFeatures = response[:categorisedFeatures].transform_values do |feature_data|
  # 遍历并处理historical数组中的每个条目
  updated_historical = feature_data[:historical].map do |historical_entry|
    # 将usageByMonth哈希转换为{month: k, value: v}格式的数组
    refactored_usage = historical_entry[:usageByMonth]&.map { |month, value| { month: month, value: value } }
    # 合并更新后的usageByMonth到原条目
    historical_entry.merge(usageByMonth: refactored_usage)
  end
  # 将更新后的historical数组合并回原feature数据
  feature_data.merge(historical: updated_historical)
end

代码解释

  • 使用transform_values方法:直接对哈希的每个value进行处理,同时保留原始的顶级键,完美解决键名丢失问题。
  • 简化层级访问:feature_data直接是categorisedFeatures中对应键的value哈希,无需用dig(1)去取值,代码更直观。
  • 避免重复生成:每个historical条目只被处理一次,map操作仅用于转换数组元素,不会额外生成重复数据。

内容的提问来源于stack exchange,提问作者Laura Gaxiola

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 07:27:49