Forums | Admin

Discussion Forums: help

Start New Thread Start New Thread
Message: 60455
BY: James Gray (bbazzarrakk)
DATE: 2008-09-15 14:46
SUBJECT: RE: Specifying converters column by column?

 

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


Thread View

Thread Author Date
Specifying converters column by column?Michael Parker2008-09-15 10:52
      RE: Specifying converters column by column?James Gray2008-09-15 14:46
            RE: Specifying converters column by column?Michael Parker2008-09-22 06:55

Post a followup to this message