如何将哈希保存到CSV中

The*_*end 36 ruby csv hash append

我是红宝石的新人,所以请原谅我的愚蠢.

我有一个包含两列的CSV.一个用于动物名称,一个用于动物类型.我有一个散列,其中所有键都是动物名称,值是动物类型.我想在不使用fasterCSV的情况下将哈希写入CSV.我想到了几个最简单的想法..这里是基本的布局.

require "csv"

def write_file
  h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }

  CSV.open("data.csv", "wb") do |csv|
    csv << [???????????]
  end
end
Run Code Online (Sandbox Code Playgroud)

当我打开文件从中读取时,我打开它File.open("blabla.csv", headers: true) 是否可以以相同的方式写回文件?

Joe*_*ins 58

如果您想要列标题,并且您有多个哈希:

require 'csv'
hashes = [{'a' => 'aaaa', 'b' => 'bbbb'}]
column_names = hashes.first.keys
s=CSV.generate do |csv|
  csv << column_names
  hashes.each do |x|
    csv << x.values
  end
end
File.write('the_file.csv', s)
Run Code Online (Sandbox Code Playgroud)

(在Ruby 1.9.3-p429上测试)


Sła*_*osz 41

试试这个:

require 'csv'
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
CSV.open("data.csv", "wb") {|csv| h.to_a.each {|elem| csv << elem} }
Run Code Online (Sandbox Code Playgroud)

将导致:

1.9.2-p290:~$ cat data.csv 
dog,canine
cat,feline
donkey,asinine
Run Code Online (Sandbox Code Playgroud)

  • 当我升起时,我的回答是错误的.:) (4认同)

Tom*_*ssi 24

我认为原始问题的最简单的解决方案:

def write_file
  h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }

  CSV.open("data.csv", "w", headers: h.keys) do |csv|
    csv << h.values
  end
end
Run Code Online (Sandbox Code Playgroud)

使用多个哈希共享相同的键:

def write_file
  hashes = [ { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' },
             { 'dog' => 'rover', 'cat' => 'kitty', 'donkey' => 'ass' } ]

  CSV.open("data.csv", "w", headers: hashes.first.keys) do |csv|
    hashes.each do |h|
      csv << h.values
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 在 *ruby v2.5.3* 中,至少在 `CSV.open 中需要 `write_headers: true` (3认同)

rud*_*ph9 12

CSV可以按任何顺序获取哈希值,排除元素,并省略不在其中的参数 HEADERS

require "csv"
HEADERS = [
  'dog',
  'cat',
  'donkey'
]

def write_file

  CSV.open("data.csv", "wb", :headers => HEADERS, :write_headers => true) do |csv|
    csv << { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
    csv << { 'dog' => 'canine'}
    csv << { 'cat' => 'feline', 'dog' => 'canine', 'donkey' => 'asinine' }
    csv << { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine', 'header not provided in the options to #open' => 'not included in output' }
  end
end

write_file # => 
# dog,cat,donkey
# canine,feline,asinine
# canine,,
# canine,feline,asinine
# canine,feline,asinine
Run Code Online (Sandbox Code Playgroud)

这使得使用CSV类更加灵活和可读.