CommonThread

Ruby CSV

Posted by anthony crumley, Wed Nov 21 21:43:00 UTC 2007

Comma delimited files are still used for importing and exporting of data. The Ruby Standard Library includes a class for manipulating them. When a file is read each row is converted to an array with each element of the array being a string. Files are created by writing out arrays. Following is a marketing email example.

File of people to send an email to.

John,Doe,john@commonthread.com
Peter,Rabbit,peter@commonthread.com
Billy,Goat,billy@commonthread.com

Creating the file.

require 'csv'

csv = CSV.open('MarketingEmail.csv', 'w')
csv << ['John', 'Doe', 'john@commonthread.com']
csv << ['Peter', 'Rabbit', 'peter@commonthread.com']
csv << ['Billy', 'Goat', 'billy@commonthread.com']
csv.close

Sending emails to each person in the file.

require 'csv'

reader = CSV.open('MarketingEmail.csv', 'r')
reader.each do |row|
  ...
  to = row[2]
  body = "Dear #{row[0]}," ...
  ...
end

Filed Under: | Tags:

Comments

  1. Ben 11.22.07 / 23PM
    is there any way to tell it that the first line is a header row and use those names as a symbol or string to access the columns rather than numbers?
  2. Anthony 11.23.07 / 06AM
    There does not appear to be but the documentation is very sparse.

Have your say

A name is required. You may use HTML in your comments.




Recent Articles

Categories