如何将散列保存到 CSV 中 [英] How to save a hash into a CSV

查看:28
本文介绍了如何将散列保存到 CSV 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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

这篇关于如何将散列保存到 CSV 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆