在 Ruby 中将数组输出到 CSV
使用 Ruby 将 CSV 文件读入数组很容易,但我找不到任何关于如何将数组写入 CSV 文件的好的文档。谁能告诉我该怎么做?
如果重要的话,我正在使用 Ruby 1.9.2。
It's easy enough to read a CSV file into an array with Ruby but I can't find any good documentation on how to write an array into a CSV file. Can anyone tell me how to do this?
I'm using Ruby 1.9.2 if that matters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
到文件:
到字符串:
这是 CSV 的当前文档:(直到 3.1.1 才替换 1.9.2)
https://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/ CSV.html#class-CSV-label-Writing
而 3.1.2 至最新版本(截至本次编辑为 3.2.2)。
https://ruby-doc.org/3.2.2/stdlibs/csv /CSV.html
To a file:
To a string:
Here's the current documentation on CSV: (until 3.1.1 just replace 1.9.2)
https://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#class-CSV-label-Writing
while 3.1.2 up to latest (3.2.2 as of this edit).
https://ruby-doc.org/3.2.2/stdlibs/csv/CSV.html
如果您有一个数据数组的数组:
那么您可以使用以下内容将其写入文件,我认为这要简单得多:
If you have an array of arrays of data:
Then you can write this to a file with the following, which I think is much simpler:
我把它简化为一行。
在一行中执行所有上述操作并保存到 csv。
注意:
要将活动记录数据库转换为 csv,我认为嗯@tamouse,在不阅读 csv 源代码的情况下
,这个要点对我来说有点令人困惑,但一般来说,假设数组中的每个散列具有相同数量的 k/ v 对 &键始终相同,顺序相同(即,如果您的数据是结构化的),这应该执行以下操作:
如果您的数据不是结构化的,这显然是行不通的
I've got this down to just one line.
Do all of the above and save to a csv, in one line.
NOTE:
To convert an active record database to csv would be something like this I think
Hmm @tamouse, that gist is somewhat confusing to me without reading the csv source, but generically, assuming each hash in your array has the same number of k/v pairs & that the keys are always the same, in the same order (i.e. if your data is structured), this should do the deed:
If your data isn't structured this obviously won't work
如果有人感兴趣,这里有一些俏皮话(以及关于 CSV 中类型信息丢失的注释):
注意:CSV 会丢失所有类型信息,您可以使用 JSON 来保留基本类型信息,或者转到详细信息(但更容易)人类可编辑)YAML 来保留所有类型信息——例如,如果您需要日期类型,它将成为 CSV 和 CSV 中的字符串。 JSON。
If anyone is interested, here are some one-liners (and a note on loss of type information in CSV):
Note: CSV loses all type information, you can use JSON to preserve basic type information, or go to verbose (but more easily human-editable) YAML to preserve all type information -- for example, if you need date type, which would become strings in CSV & JSON.
基于 @boulder_ruby 的答案,这就是我正在寻找的内容,假设
us_eco
包含我的要点中的 CSV 表。更新了要点 https://gist.github.com/tamouse/4647196
Building on @boulder_ruby's answer, this is what I'm looking for, assuming
us_eco
contains the CSV table as from my gist.Updated the gist at https://gist.github.com/tamouse/4647196
我自己也在为此苦苦挣扎。这是我的看法:
https://gist.github.com/2639448:
Struggling with this myself. This is my take:
https://gist.github.com/2639448: