如何将哈希输出到CSV行

lei*_*ifg 7 ruby csv

我想将哈希映射到CSV行.

哈希中有几个对象:

person1 = {'first_name' => 'John', 'second_name' => 'Doe', 'favorite_color' => 'blue', 'favorite_band' => 'Backstreet Boys'}
person2 = {'first_name' => 'Susan', 'favorite_color' => 'green', 'second_name' => 'Smith'}
Run Code Online (Sandbox Code Playgroud)

我想将其转换为CSV文件,其中键为列,每行的值.

我可以通过创建CSV::Row这样的方式轻松创建标题:

h = CSV::Row.new(all_keys_as_array,[],true)
Run Code Online (Sandbox Code Playgroud)

我不能依赖顺序而且更重要的是,并非所有的值都会被填充.

但是,当我现在尝试通过<<和数组向表中添加行时,将忽略标题的映射.它必须是正确的顺序.

为了证明这一点,我写了这个小脚本:

require 'csv'

person1 = {'first_name' => 'John', 'second_name' => 'Doe', 'favorite_color' => 'blue', 'favorite_band' => 'Backstreet Boys'}
person2 = {'first_name' => 'Susan', 'favorite_color' => 'green', 'second_name' => 'Smith'}

persons = [person1, person2]
all_keys_as_array = %w{first_name second_name favorite_color favorite_band}

h = CSV::Row.new(all_keys_as_array,[],true)
t = CSV::Table.new([h])

persons.each do |p|
  r = CSV::Row.new([],[],false)
  p.each do |k, v|
    r << {k => v}
  end
  t << r
end

puts t.to_csv
Run Code Online (Sandbox Code Playgroud)

我希望这个输出:

first_name,last_name,favorite_color,favorite_band
John,Doe,blue,Backstreet Boys
Susan,Smith,green,
Run Code Online (Sandbox Code Playgroud)

取而代之的是它们出现时的顺序值.所以输出是这样的:

first_name,second_name,favorite_color,favorite_band
John,Doe,blue,Backstreet Boys
Susan,green,Smith
Run Code Online (Sandbox Code Playgroud)

最奇怪的是,当我通过查找时['key']获得正确的值:

puts "favorite_bands: #{t['favorite_band']}"
> favorite_bands: [nil, "Backstreet Boys", nil]
Run Code Online (Sandbox Code Playgroud)

那么有没有办法像我期望的那样写入CSV文件?

Ben*_*ate 5

您可以迭代列名称

persons.each do |person|
  r = CSV::Row.new([],[],false)
  all_keys_as_array.each do |key|
    r << person[key]
  end
  t << r
end
Run Code Online (Sandbox Code Playgroud)


lei*_*ifg 5

目前的建议都有效,所以谢谢你.

但是,我通过使用CSV :: Row#字段偶然发现了更优雅的解决方案.

然后我可以将CSV行转换为正确的数组,然后再将其添加到表中:

t << r.fields(*all_keys_as_array)
Run Code Online (Sandbox Code Playgroud)