Forums | Admin

Discussion Forums: help

Start New Thread Start New Thread

 

By: Michael Parker
RE: Specifying converters column by column? [ reply ]  
2008-09-22 06:55

Excellent, thank you for the example!

Michael

By: James Gray
RE: Specifying converters column by column? [ reply ]  
2008-09-15 14:46
You can easily do what you are asking for. If you make a converter that takes two arguments, the second argument will contain information about the field you are currently converting. Using that, here's an example of how to convert by index or column name:

#!/usr/bin/env ruby -wKU

require "pp"

require "rubygems"
require "faster_csv"

data = <<END_DATA
one,two,three
1,2,3
4,5,6
END_DATA

col3_to_int = lambda { |field, info| info.index == 2 ? field.to_i : field }
pp FCSV.parse(data, :converters => col3_to_int)
# >> [["one", "two", 0], ["1", "2", 3], ["4", "5", 6]]

three_to_int = lambda do |field, info|
info.header == "three" ? field.to_i : field
end
pp FCSV.parse(data, :headers => true, :converters => col3_to_int).to_a
# >> [["one", "two", "three"], ["1", "2", 3], ["4", "5", 6]]

__END__

Hope that helps.

James Edward Gray II

By: Michael Parker
Specifying converters column by column? [ reply ]  
2008-09-15 10:52
When parsing a CSV file I usually know what data type to expect in each column, is there a way to specify which converter to use on each column? As far as I can tell, the :converters option allows one to determine converter precedence, but the same setting seems to be used for all columns.