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

嵌套ResultSet数组迭代异常:CSV导出报错修复咨询

解决嵌套数组格式的ResultSet导出CSV问题

问题出在大数据量返回的items数组中混入了子数组,原代码直接遍历每个元素调用values方法,遇到数组元素时自然会抛出undefined method 'values' for #<Array:错误——因为数组没有这个方法。

基础修复方案(扁平化数组)

直接用flatten方法将嵌套数组展开为一维哈希数组,确保所有元素都是可处理的哈希:

def to_file(items)
  flattened_items = items.flatten
  CSV.open('my_file.csv', 'wb') do |file|
    # 空数组时跳过表头写入,避免报错
    file << flattened_items.first.keys unless flattened_items.empty?
    flattened_items.each { |item| file << item.values }
  end
end

flatten会自动拆解嵌套的子数组,把整个结构转为[hash, hash, ...]的一维格式,这样原有的遍历逻辑就能正常工作。同时增加空数组判断,防止没有数据时调用first.keys抛出异常。

手动遍历判断(避免过度扁平化)

如果担心flatten会意外处理哈希内部的数组值(你的场景里应该不存在,但可以做更精准的处理),可以手动遍历每个元素,区分哈希和数组:

def to_file(items)
  all_items = []
  items.each do |element|
    # 元素是数组就合并到all_items,否则直接添加
    element.is_a?(Array) ? all_items.concat(element) : all_items << element
  end

  CSV.open('my_file.csv', 'wb') do |file|
    file << all_items.first.keys unless all_items.empty?
    all_items.each { |item| file << item.values }
  end
end

增强版:处理哈希键不一致的情况

如果ResultSet中存在键不统一的哈希(比如部分数据缺少某些字段),直接用values会导致CSV列错位,此时可以先收集所有唯一键作为表头,再按顺序填充值:

def to_file(items)
  flattened_items = items.flatten
  return if flattened_items.empty?

  # 收集所有出现过的键,去重后作为表头
  headers = flattened_items.flat_map(&:keys).uniq
  CSV.open('my_file.csv', 'wb') do |file|
    file << headers
    flattened_items.each do |item|
      # 按表头顺序取对应值,缺失字段填空字符串
      file << headers.map { |key| item[key] || "" }
    end
  end
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:15:39