在ruby中智能地将散列数组转换为CSV [英] Smartly converting array of hashes to CSV in ruby

查看:148
本文介绍了在ruby中智能地将散列数组转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换CSV文件中的散列数组。我发现的各种方法涉及到在数组中插入散列值:

I need to convert an array of hashes in a CSV file. The various methods I found involve inserting in the array the hash values:

class Array
  def to_csv(csv_filename="hash.csv")
    require 'csv'
    CSV.open(csv_filename, "wb") do |csv|
      csv << first.keys # adds the attributes name on the first line
      self.each do |hash|
        csv << hash.values
      end
    end
  end
end

不幸的是,这个方法需要数组中的每个元素都是完整的,例如当我有这个数组,甚至不会返回一个有效的csv:

Unfortunately this method requires that each element in the array is complete, for example when I have this array it won't even return a valid csv:

myarray = [
  {foo: 1, bar: 2, baz: 3},
  {bar: 2, baz: 3},
  {foo: 2, bar: 4, baz: 9, zab: 44}
]

推荐答案

创建一个csv以找到所有可能的标头,并按正确的顺序分配值,

如何:

What about:

class Array
  def to_csv(csv_filename="hash.csv")
    require 'csv'
    # Get all unique keys into an array:
    keys = self.flat_map(&:keys).uniq
    CSV.open(csv_filename, "wb") do |csv|
      csv << keys
      self.each do |hash|
        # fetch values at keys location, inserting null if not found.
        csv << hash.values_at(*keys)
      end
    end
  end
end

这篇关于在ruby中智能地将散列数组转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆