All You Need To Know To Create & Parse CSV in Ruby

asha's Avatar author of All You Need To Know To Create & Parse CSV in Ruby
This is an article on All You Need To Know To Create & Parse CSV in Ruby in Ruby on Rails.
CSV has become a common and popular format for many uses, primarily for address book, reports, and other tabular data export requirements. For example, you can download your GMail address book in CSV format and import into Microsoft Outlook or Thunderbird, not complex propriety formats involved, you can also take backups in CSV format for later use. I have previously discussed & written about reading and creating CSV in languages like Perl, Python & PHP.

In this article we see how to parse and create CSV files. We'll be using a native Ruby module CSV and another module FasterCSV which tends to be a little less resource intensive than the native module.

Installation



Installation is required only for FasterCSV, the other module CSV comes with Ruby, ready to use.

The best, easiest & preferred method for installing FasterCSV is using RubyGems, just issue the following command as a root user:

Code:
$ gem install fastercsv

Creating CSV



Both the modules' usage syntax is pretty much the same, just replace the class names to use either. Follow the code below to write data into a CSV file:

Code: Ruby
FasterCSV.open("data_file.csv", "w") do |csv_obj|
    csv_obj << ["1", "Jasbir", "Kolkata", "8"]
    csv_obj << ["2", "Shabbir", "Ahmedabad", "6"]
    ## and so on, you can do this in a loop
end

At times, you might want to get the CSV in a string instead of writing to a file, here's how to do that:

Code: Ruby
string_data_csv = FasterCSV.generate("data_file.csv", "w") do |csv_obj|
    csv_obj << ["1", "Jasbir", "Kolkata", "8"]
    csv_obj << ["2", "Shabbir", "Ahmedabad", "6"]
    ## and so on, you can do this in a loop
end

Parsing CSV



Parsing CSV data is even easier, just checkout the example below:

Code: Ruby
CSV.foreach("data_file.csv") do |row|
  ## do whatever you want to do with the row, I'll just print it
  puts row.join(' | ')
end

# You may even read all the rows into an array
csv_rows = CSV.read("data_file.csv")

# Or you may want to parse line by line yourself
csv_row = CSV.parse("PHP,Perl,Python,Ruby")