dfrankow dfrankow - 1 year ago 129
Ruby Question

How do you use Ruby CSV converters?

Suppose you have the following file:

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

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

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)

What gives?

I've read the docs, but I don't get it.

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.

Answer Source

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.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download