如何保存一个散列成CSV [英] How to save a hash into a CSV
问题描述
我在红宝石是新的,所以请原谅noobishness。
I am new in ruby so please forgive the noobishness.
我有两列的CSV。一个用于动物的名称和一个用于动物类型。
我有所有的键是动物的名称和动物被类型值的哈希值。我还想写哈希到CSV不使用fasterCSV。我已经想到了一些想法是什么将是最简单..这里是基本布局。
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,标题:真)
有没有可能写回文件以同样的方式?
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
这篇关于如何保存一个散列成CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!