# Ruby SmarterCSV Gem

> A quick look at using the SmarterCSV gem.

- Canonical: https://dennisokeeffe.com/blog/2022-04-06-ruby-smartercsv-gem
- Published: 2022-04-06
- Updated: 2022-04-06
- Tags: ruby

This post will cover the [SmarterCSV](https://github.com/tilo/smarter_csv) gem in action.

## Prerequisites

- We'll be using [IRB](https://github.com/ruby/irb) to play around with the gem.

## Getting started

We will create a new project, initialize it with Bundler and add the SmarterCSV gem.

```s
$ 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:

```csv
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.

```s
$ 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.

```s
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.

```s
: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

- [IRB](https://github.com/ruby/irb)
- [Bundler](https://bundler.io/)
- [SmarterCSV](https://github.com/tilo/smarter_csv)

_Photo credit: [`marekpiwnicki`](https://unsplash.com/@marekpiwnicki)_
