Ruby SmarterCSV Gem
Published: Apr 6, 2022
Last updated: Apr 6, 2022
This post will cover the SmarterCSV gem in action.
Prerequisites
- We'll be using IRB to play around with the gem.
Getting started
We will create a new project, initialize it with Bundler and add the SmarterCSV gem.
$ mkdir demo-smartercsv $ cd demo-smartercsv # Add a CSV file $ touch example.csv # initialise Bundler project $ bundle init # RSpec added for testing $ bundle add smarter_csv
At this stage, our project is now ready to start working with.
Populating the CSV file
Update example.csv
with the following:
first_name,last_name,age,height John,Doe,19,183 Jane,Doe,20,170 Bill,Ly,29,177 Jimmy,Lu,43,159 Stacy,Jones,26,164
At this stage, we are ready to play around with the gem.
Using IRB to interact with SmarterCSV
Open up the IRB console and start by loading the gem.
$ irb irb(main):001:0> require 'smarter_csv' => true
At this stage, we can see SmarterCSV at work by simply invoking the process
method on the SmarterCSV
class with a path to the file.
irb(main):002:0> SmarterCSV.process('./example.csv') => [{:first_name=>"John", :last_name=>"Doe", :age=>19, :height=>183}, {:first_name=>"Jane", :last_name=>"Doe", :age=>20, :height=>170}, {:first_name=>"Bill", :last_name=>"Ly", :age=>29, :height=>177}, {:first_name=>"Jimmy", :last_name=>"Lu", :age=>43, :height=>159}, {:first_name=>"Stacy", :last_name=>"Jones", :age=>26, :height=>164}]
At this stage, the data is already in an array of hashes that makes it easier for us to start mucking around.
That is effectively it. There are arguments you can pass to process
that can do handy things like chunking or renaming values.
:003:0> SmarterCSV.process('./example.csv', {:chunk_size => 2, :key_mapping => {:first_name => :first, :last_name => [[{:first=>"John", :last=>"Doe", :age=>19, :height=>183}, {:first=>"Jane", :last=>"Doe", :age=>20, :height=>170}], [{:first=>"Bill", :last=>"Ly", :age=>29, :height=>177}, {:first=>"Jimmy", :last=>"Lu", :age=>43, :height=>159}], [{:first=>"Stacy", :last=>"Jones", :age=>26, :height=>164}]]
Summary
Today's post was a quick tip on a gem for parsing CSV files with less effort.
Resources and further reading
Photo credit: marekpiwnicki
Ruby SmarterCSV Gem
Introduction