File tree Expand file tree Collapse file tree 2 files changed +41
-1
lines changed Expand file tree Collapse file tree 2 files changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010
1111For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
1212
13- _ 1161 TILs and counting..._
13+ _ 1162 TILs and counting..._
1414
1515---
1616
@@ -915,6 +915,7 @@ _1161 TILs and counting..._
915915- [ Evaluating One-Off Commands] ( ruby/evaluating-one-off-commands.md )
916916- [ Exclude Values From An Array] ( ruby/exclude-values-from-an-array.md )
917917- [ Expect A Method To Be Called And Actually Call It] ( ruby/expect-a-method-to-be-called-and-actually-call-it.md )
918+ - [ Extract A Column Of Data From A CSV File] ( ruby/extract-a-column-of-data-from-a-csv-file.md )
918919- [ FactoryGirl Sequences] ( ruby/factory-girl-sequences.md )
919920- [ Fail] ( ruby/fail.md )
920921- [ Find The Min And Max With A Single Call] ( ruby/find-the-min-and-max-with-a-single-call.md )
Original file line number Diff line number Diff line change 1+ # Extract A Column Of Data From A CSV File
2+
3+ Let's say I have just downloaded a medium-sized CSV of data onto my hard drive.
4+ I want to exact one column of data from that CSV to inject into some other
5+ tool/process.
6+
7+ Here is how I'd go about doing that with Ruby.
8+
9+ ``` ruby
10+ require ' csv'
11+
12+ filename = " #{ Dir .home} /Downloads/file.csv"
13+ column_index = 2 # zero-indexed column of interest
14+
15+ # an array of collecting the values I want to extract
16+ col_data = []
17+
18+ # read in the CSV into memory
19+ csv_data = CSV .read(filename)
20+
21+ # pop headers out of the top of the array
22+ csv_data.shift
23+
24+ # grab the column of interest from each row
25+ csv_data.each { |row | col_data << row[column_index] }
26+
27+ # do something with the extract column of data
28+ comma_separated_list = col_data.join(' , ' )
29+ system " command -v pbcopy >/dev/null 2>&1 && echo '#{ comma_separated_list } ' | pbcopy"
30+ ```
31+
32+ All but the last two lines are pretty standard. We identify the file and column
33+ of interest. Read in the CSV from that file and ditch the headers. Then we grab
34+ that column's value for every entry in the CSV.
35+
36+ Then we need to do something with that data.
37+
38+ In my case, I want to turn those values into a comma-separated list and put it
39+ on my clipboard. Those last two lines do just that.
You can’t perform that action at this time.
0 commit comments