From 15d1472dddb5b83042719fbfb6c0c2ea6af22fab Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 26 Oct 2021 13:59:16 -0500 Subject: [PATCH] Add Extract A Column Of Data From A CSV File as a ruby TIL --- README.md | 3 +- ...xtract-a-column-of-data-from-a-csv-file.md | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 ruby/extract-a-column-of-data-from-a-csv-file.md diff --git a/README.md b/README.md index 6685acf..ee98a76 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/ruby/extract-a-column-of-data-from-a-csv-file.md b/ruby/extract-a-column-of-data-from-a-csv-file.md new file mode 100644 index 0000000..f087a06 --- /dev/null +++ b/ruby/extract-a-column-of-data-from-a-csv-file.md @@ -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.