Ruby:如何使用dump方法将数据输出到csv文件? [英] Ruby: how can use the dump method to output data to a csv file?

查看:195
本文介绍了Ruby:如何使用dump方法将数据输出到csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用ruby标准csv lib将对象的arr转储到名为'a.csv'的csv.file

I try to use the ruby standard csv lib to dump out the arr of object to a csv.file , called 'a.csv'

http://ruby-doc.org/stdlib -1.9.3 / libdoc / csv / rdoc / CSV.html#method-c-dump

dump(ary_of_objs, io = "", options = Hash.new)

转储到文件?
有没有这样的例子存在和帮助。我google上没有例子为我做的...

but in this method, how can i dump into a file? there is no such examples exists and help. I google it no example to do for me...

此外,文档说...


你可以提供的下一个方法是一个名为
csv_headers()的实例方法。这个方法期望返回
文档的第二行(再次作为一个Array),用来给每个
列一个头。默认情况下,:: load将设置一个实例变量,如果
字段头以@字符开头或调用send()传递
头作为方法名和字段值作为参数。这个
方法只在数组的第一个对象上调用。

The next method you can provide is an instance method called csv_headers(). This method is expected to return the second line of the document (again as an Array), which is to be used to give each column a header. By default, ::load will set an instance variable if the field header starts with an @ character or call send() passing the header as the method name and the field value as an argument. This method is only called on the first object of the Array.

任何人都知道如何传递实例方法csv_headers )到这个转储函数?

Anyone knows how to pass the instance method csv_headers() to this dump function?

推荐答案

我还没有测试过,但看起来io应该设置为文件。根据你链接的文档,io参数可以用来序列化到一个文件

I haven't tested this out yet, but it looks like io should be set to a file. According to the doc you linked "The io parameter can be used to serialize to a File"

像这样:

f = File.open(filename)

dump(ary_of_objs,io = f,options = Hash.new)

这篇关于Ruby:如何使用dump方法将数据输出到csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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