是否有一个 Ruby CSV 解析器可以生成列 getter 方法?
我试图用 Ruby 概括一种数据检索机制,但似乎找不到一种方法来检索 CSV 文件并使用点运算符访问行的列之一,如下所示:
假设我有一个 CSV 表:
#some_file.csv
name,age
albert,13
我从中创建了一个 FasterCSV 表:
a = FasterCSV.new(File.open('some_file.csv'), :headers => :first_row)
然后,当访问一行时,我希望能够说:
a[0].name
=> 'albert'
而不是“
a[0]['name']
=> 'albert'
任何人都知道如何做到这一点?”
I'm trying to generalize a data retrieval mechanism with Ruby, and can't seem to find a way to retrieve a CSV file and access one of the row's columns by using a dot operator like so:
Let's say I have a CSV table:
#some_file.csv
name,age
albert,13
And I create a FasterCSV table from it:
a = FasterCSV.new(File.open('some_file.csv'), :headers => :first_row)
Then, when accessing a row, I'd like to be able to say:
a[0].name
=> 'albert'
Instead of
a[0]['name']
=> 'albert'
Anyone know how to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,如果你找不到,你可以随时对
FasterCSV::Row
类进行猴子补丁,例如:(我自己还没有尝试过代码。)
PS。当您概括数据检索机制时,我假设 CSV 只是您计划支持的几个数据源之一。合乎逻辑的事情是为每个数据源创建一个包装类,并使用一些通用接口(可能会也可能不会使用访问器来访问行字段)。但在下面它仍然应该使用
[]
方法以通常的方式访问 CSV 行。那么,正如 Glenjamin 已经问过的那样,你为什么需要这个? ;)Well, if you don't find one, you can always monkey-patch
FasterCSV::Row
class, something like:(Haven't tried the code myself.)
PS. As you are generalizing data retrieval mechanism, I assume that CSV is just one of several data sources you plan to support. The logical thing then would be to create a single wrapper class for each of your data sources, with some common interface (which might or might not use accessors for accessing row fields). But underneath it should still access CSV row usual way, using
[]
method. So, as Glenjamin already asked, why do you need this at all? ;)最简单的答案是……为什么?
我假设它主要是作为语法糖,所以这里有一个小猴子补丁,应该可以完成您想要的操作:
请注意,任何与现有 Row 方法冲突的字段名称都不会像这样工作。
The simplest answer would be.. why?
I'll assume its mostly as syntactic sugar, so here's a little monkeypatch that should do what it is you want:
Note that any field names conflicting with existing Row methods wont work like this.