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

Discussion in 'Ruby on Rails' started by asha, Dec 10, 2012.

  1. asha

    asha New Member

    Nov 9, 2006
    Likes Received:
    Trophy Points:
    Home Page:
    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 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:

    $ 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:"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
    At times, you might want to get the CSV in a string instead of writing to a file, here's how to do that:

    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

    Parsing CSV

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

    CSV.foreach("data_file.csv") do |row|
      ## do whatever you want to do with the row, I'll just print it
      puts row.join(' | ')
    # You may even read all the rows into an array
    csv_rows ="data_file.csv")
    # Or you may want to parse line by line yourself
    csv_row = CSV.parse("PHP,Perl,Python,Ruby")

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice