如何将哈希保存到 CSV如何将、CSV

2023-09-07 02:08:52 作者:大姨妈的诱惑i

我是 ruby​​ 新手,所以请见谅.

I am new in ruby so please forgive the noobishness.

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

I have a CSV with two columns. One for animal name and one for animal type. I have a hash with all the keys being animal names and the values being animal type. I would like to write the hash to the CSV without using fasterCSV. I have thought of several ideas what would be easiest.. here is the basic layout.

require "csv"

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

  CSV.open("data.csv", "wb") do |csv|
    csv << [???????????]
  end
end

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

When I opened the file to read from it I opened it File.open("blabla.csv", headers: true) Would it be possible to write back to the file the same way?

推荐答案

试试这个:

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

结果:

1.9.2-p290:~$ cat data.csv 
dog,canine
cat,feline
donkey,asinine