是否有一个 Ruby CSV 解析器可以生成列 getter 方法?

发布于 2024-08-24 06:17:04 字数 447 浏览 4 评论 0原文

我试图用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千と千尋 2024-08-31 06:17:04

好吧,如果你找不到,你可以随时对 FasterCSV::Row 类进行猴子补丁,例如:(

class FasterCSV::Row
  def method_missing(m,*args)
    if self.field?(m.to_s)
      return self[m.to_s]
    else
      super
    end
  end
end

我自己还没有尝试过代码。)

PS。当您概括数据检索机制时,我假设 CSV 只是您计划支持的几个数据源之一。合乎逻辑的事情是为每个数据源创建一个包装类,并使用一些通用接口(可能会也可能不会使用访问器来访问行字段)。但在下面它仍然应该使用 [] 方法以通常的方式访问 CSV 行。那么,正如 Glenjamin 已经问过的那样,你为什么需要这个? ;)

Well, if you don't find one, you can always monkey-patch FasterCSV::Row class, something like:

class FasterCSV::Row
  def method_missing(m,*args)
    if self.field?(m.to_s)
      return self[m.to_s]
    else
      super
    end
  end
end

(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? ;)

丢了幸福的猪 2024-08-31 06:17:04

最简单的答案是……为什么?

我假设它主要是作为语法糖,所以这里有一个小猴子补丁,应该可以完成您想要的操作:

class FasterCSV::Row
  def method_missing(row)
    field(row)
  end
end

请注意,任何与现有 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:

class FasterCSV::Row
  def method_missing(row)
    field(row)
  end
end

Note that any field names conflicting with existing Row methods wont work like this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文