Using Ruby on CSV Files
I’m working with some different systems for a conference I’m working on. We’re using RegOnline to handle the registrations. One of the things that I need to do is get a list of people who have registered on RegOnline and post them on our conference website. Our conference site is plain html and I don’t want to have to type in each person who registers. I can download a csv file from RegOnline. I want to write a script that reads the downloaded csv file and makes an html file for the website. I hadn’t done much with csv files before, but here’s a basic script that pretty much does what I want. (I still have to put html tags in, but that should be pretty easy.)
#!/Users/maryh/Software/rubies/2.2.3/bin/ruby require 'csv' unless ARGV.count == 1 puts "SYNTAX: generate_list_of_participants <input.csv>" puts "" puts "Expecting the csv file downloaded from regonline." exit(0) end inputfile = ARGV.first my_csv = CSV.read("#{inputfile}", { headers: true }) # my_csv now has an array where each line in the file is an entry # headers: true means the first line is headers and we don't want them my_csv.each do |e| if e[4] == 'Other' puts "#{e[1]} #{e[2]} #{e[5]} #{e[6]}" else puts "#{e[1]} #{e[2]} #{e[4]} #{e[6]}" end end
The first part of the script is just giving the syntax and checking that there’s a filename on the command line. The second part, reads the entire file into and array (of arrays) called my_csv. The bit headers:true means that the first line in the csv file is a header row and it won’t read that line in.
Then I just cycle through the array and print out the fields that I want. My csv file has a job in field e[4]. If it’s other, I want to print what they typed in for their job (in field e[5]) instead of the ‘Other’ string.
That’s pretty much it. There are some other things that I need to do, but to get started, this does the job.
Things to do:
-sort the array in alphabetical order on field e[2] (lastname)
-check that the attendee has actually paid, if they’re submitting a check or wire transfer