Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSV Class to parse a .csv file in Ruby

Tags:

ruby

csv

I'm using Ruby 1.9.3 and I've discovered the CSV class, but I can't get it to work. Basically, I want to be able to manipulate the various options for the CSV, and then pull a .csv file into an array to work with, eventually pushing that array back out into a new file.

This is what I have currently:

require 'csv'
CSV_Definition = CSV.New(:header_converters => :symbol)

CSV_Total = CSV.Read(File.Path("C:\Scripts\SQL_Log_0.csv"))

However, I don't think this is the right way to change the :header_converters. Currently I can't get IRB working to parse these pieces of code (I'm not sure how to require 'csv' in IRB) so I don't have any particular error message. My expectations for this will be to create an array (CSV_Total) that has a header with no symbols in it. The next step is to put that array back into a new file. Basically it would scrub CSV files.

like image 949
Sean Long Avatar asked May 29 '13 18:05

Sean Long


1 Answers

Ruby used to have it's own built in CSV library which has been replaced with FasterCSV as of version 1.9, click on the link for documentation.

All that's required on your part is to use to import the CSV class via require 'csv' statement wherever you want to use it and process accordingly. It's pretty easy to build an array with the foreach statement, e.g.,:

people.csv

Merry,Christmas
Hal,Apenyo
Terri,Aki
Willy,Byte

process_people.rb

require 'csv'    

people = []

CSV.foreach(File.path("people.csv")) do |row|
    # Where row[i] corresponds to a zero-based value/column in the csv
    people << [row[0] + " " + row[1]]
end

puts people.to_s 
=> [["Merry Christmas"], ["Hal Apenyo"], ["Terri Aki"], ["Willy Byte"]]
like image 156
Noz Avatar answered Oct 07 '22 00:10

Noz