csv-tool is a simple gem that makes it easy to manipulate .csv files in ruby (in particular using something like pry).
Why? Because Excel’s built in “scripting” sucks. There are so many simple things I’d like to do with a spread sheet which just feel clunky using the excel commans.
Ruby is much nicer and I’d much rather do data hacking using ruby + pry than with excel.
The gem reads in the CSV file expecting the first line to include the headers. Each hearder is turned into a symbol.
Each line is then read in and converted into a hash of :header => value which is added to an array.
In the end the csv file below will look like:
[ {:Name => 'David', :Age => '31', :Location => 'Brisbane'}, {:Name => 'Ian', :Age => '45', :Location => 'Adelaide'}, ... ]
Admittedly this is fairly inefficient, however, this is a hacky tool designed for hacky jobs :)
Let’s say we have some very simple data: test.csv
Name, Age, Location David, 31, Brisbane Ian, 45, Adelaide Tom, 22, Melbourne Simon, 18, Brisbane
To use this with csv-tool:
require 'csv-tool' data = Csv-Tool.new 'test.csv'
We can now do things like the below which returns all rows with an age > 15:
data.select{ |d| d[:Age].to_i > 15 }
There also a couple of helper methods.
data.columns will return all rows, but only with columns specified.
data.columns(:Name, :Location) [ {:Name => 'David', :Location => 'Brisbane'}, {:Name => 'Ian', :Location => 'Melbourne'} ... ]
data.headers returns the list of headers found when loading the csv file.
data.headers [:Name, :Age, :Location]
Finally this can be made even better if you combine with the descriptive-statistics gem.
-
Check out the latest master to make sure the feature hasn’t been implemented or the bug hasn’t been fixed yet.
-
Check out the issue tracker to make sure someone already hasn’t requested it and/or contributed it.
-
Fork the project.
-
Start a feature/bugfix branch.
-
Commit and push until you are happy with your contribution.
-
Make sure to add tests for it. This is important so I don’t break it in a future version unintentionally.
-
Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
Copyright © 2013 HealsJnr. See LICENSE.txt for further details.