我有一系列哈希,如下:
[{:id => 1, :name => "test", :status => "active", :desc => "test desc"}, {...}]
我需要将其转换为CSV格式。我意识到我可以使用CSV.generate
(我使用ruby 1.9)来生成CSV。
首先使用to_a
将哈希变为数组?
答案 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"