1

我有一个哈希数组,如下所示:

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

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

将散列转换为数组的第一个是一个想法to_a吗?

4

1 回答 1

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"
于 2013-04-14T11:18:23.427 回答