7

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.

1
  • 2
    Please tell us what it is that is not working, give us an example of your code, the input, the error or unexpected output, and what you expected as output. Commented May 29, 2013 at 19:26

1 Answer 1

12

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"]]
Sign up to request clarification or add additional context in comments.

1 Comment

"Ruby used to have it's own built in CSV library which has been replaced with FasterCSV as of version 1.9" To say that differently, Ruby's built-in CSV uses FasterCSV, which used to be a separate gem, but was pulled into the standard library in Ruby 1.9.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.