Using CSV Class to parse a .csv file in Ruby

18,724

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"]]
Share:
18,724

Related videos on Youtube

Sean Long
Author by

Sean Long

Updated on October 18, 2022

Comments

  • Sean Long
    Sean Long over 1 year

    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.

    • Theo
      Theo almost 11 years
      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.
  • PJP
    PJP almost 11 years
    "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.