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

    Joined:
    Nov 9, 2006
    Messages:
    44
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Homemaker
    Location:
    Kolkata
    Home Page:
    http://whatanindianrecipe.com
    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:
    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:
    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:
    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")
    
     

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