mirror of
https://github.com/jbranchaud/til
synced 2026-01-08 17:48:01 +00:00
Add Extract A Column Of Data From A CSV File as a ruby TIL
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1161 TILs and counting..._
|
||||
_1162 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -915,6 +915,7 @@ _1161 TILs and counting..._
|
||||
- [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md)
|
||||
- [Exclude Values From An Array](ruby/exclude-values-from-an-array.md)
|
||||
- [Expect A Method To Be Called And Actually Call It](ruby/expect-a-method-to-be-called-and-actually-call-it.md)
|
||||
- [Extract A Column Of Data From A CSV File](ruby/extract-a-column-of-data-from-a-csv-file.md)
|
||||
- [FactoryGirl Sequences](ruby/factory-girl-sequences.md)
|
||||
- [Fail](ruby/fail.md)
|
||||
- [Find The Min And Max With A Single Call](ruby/find-the-min-and-max-with-a-single-call.md)
|
||||
|
||||
39
ruby/extract-a-column-of-data-from-a-csv-file.md
Normal file
39
ruby/extract-a-column-of-data-from-a-csv-file.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Extract A Column Of Data From A CSV File
|
||||
|
||||
Let's say I have just downloaded a medium-sized CSV of data onto my hard drive.
|
||||
I want to exact one column of data from that CSV to inject into some other
|
||||
tool/process.
|
||||
|
||||
Here is how I'd go about doing that with Ruby.
|
||||
|
||||
```ruby
|
||||
require 'csv'
|
||||
|
||||
filename = "#{Dir.home}/Downloads/file.csv"
|
||||
column_index = 2 # zero-indexed column of interest
|
||||
|
||||
# an array of collecting the values I want to extract
|
||||
col_data = []
|
||||
|
||||
# read in the CSV into memory
|
||||
csv_data = CSV.read(filename)
|
||||
|
||||
# pop headers out of the top of the array
|
||||
csv_data.shift
|
||||
|
||||
# grab the column of interest from each row
|
||||
csv_data.each { |row| col_data << row[column_index] }
|
||||
|
||||
# do something with the extract column of data
|
||||
comma_separated_list = col_data.join(', ')
|
||||
system "command -v pbcopy >/dev/null 2>&1 && echo '#{comma_separated_list}' | pbcopy"
|
||||
```
|
||||
|
||||
All but the last two lines are pretty standard. We identify the file and column
|
||||
of interest. Read in the CSV from that file and ditch the headers. Then we grab
|
||||
that column's value for every entry in the CSV.
|
||||
|
||||
Then we need to do something with that data.
|
||||
|
||||
In my case, I want to turn those values into a comma-separated list and put it
|
||||
on my clipboard. Those last two lines do just that.
|
||||
Reference in New Issue
Block a user