All You Need To Know To Create & Parse CSV in Ruby
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:
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:
At times, you might want to get the CSV in a string instead of writing to a file, here's how to do that:
Parsing CSV data is even easier, just checkout the example below:
|All times are GMT +5.5. The time now is 13:59.|