如何使用Ruby CSV转换器? [英] How do you use Ruby CSV converters?

查看:107
本文介绍了如何使用Ruby CSV转换器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下文件:

textfield,datetimefield,numfield
foo,2008-07-01 17:50:55.004688,1
bar,2008-07-02 17:50:55.004688,2


$ b b

读取.csv的Ruby代码如下:

The Ruby code to read a .csv is something like:

#!/usr/bin/env ruby

require 'csv'

csv = CSV($stdin, :headers => true, :converters => :all)
csv.each do |row|
  print "#{row}"
  the_date = row['datetimefield'].to_date
end

该代码给出此错误消息:

That code gives this error message:

./foo2.rb:8:in `block in <main>': undefined method `to_date' for "2008-07-01 17:50:55.004688":String (NoMethodError)

有什么优点?

我读过文档,但我不知道。

编辑:是的,我可以单独解析字段。

Edit: Yes, I could parse the fields individually. The point of this question is that I want to learn how to use the documented converters feature.

推荐答案

您的日期时间不适用于这个问题匹配CSV用于决定是否应尝试日期时间转换的 CSV :: DateTimeMatcher regexp。

Your date times don't match the CSV::DateTimeMatcher regexp that CSV uses to decide whether it should attempt a date time conversion. By the looks of it it's doing so because of the fractional seconds you've got.

你可以覆盖这个常量或者编写你自己的转换器( DateTime.parse 似乎对您的字符串感到满意)

You could either overwrite that constant or write your own converter (DateTime.parse seems happy with your strings)

这篇关于如何使用Ruby CSV转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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