将哈希数组转换为csv

时间:2013-04-14 11:12:35

标签: ruby ruby-on-rails-3

我有一系列哈希,如下:

[{:id => 1, :name => "test", :status => "active", :desc => "test desc"}, {...}]

我需要将其转换为CSV格式。我意识到我可以使用CSV.generate(我使用ruby 1.9)来生成CSV。

首先使用to_a将哈希变为数组?

1 个答案:

答案 0 :(得分:0)

arr = [{:id => 1, :name => "test", :status => "active", :desc => "test desc"},{:x => 4,:l => 7}]
arr = arr.each_with_object([]) { |i,mem| mem << i.to_a  }.flatten
p arr

输出:

[:id, 1, :name, "test", :status, "active", :desc, "test desc", :x, 4, :l, 7]

<强>更新

  require 'csv'
  arr = [{:id => 1, :name => "test", :status => "active", :desc => "test desc"},{:x => 4,:l => 7}]
  arr = arr.each_with_object([]) { |i,mem| mem << i.to_a}.flatten.to_csv
  p arr

输出:

"id,1,name,test,status,active,desc,test desc,x,4,l,7\n"