From 2d697307a9b1353d2cd30c3d46389076cbda0ecd Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 29 Jun 2020 12:43:16 -0500 Subject: [PATCH] Add Parsing A CSV With Quotes In The Data as a ruby til --- README.md | 3 ++- ruby/parsing-a-csv-with-quotes-in-the-data.md | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 ruby/parsing-a-csv-with-quotes-in-the-data.md diff --git a/README.md b/README.md index 8889e60..a611832 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_928 TILs and counting..._ +_929 TILs and counting..._ --- @@ -752,6 +752,7 @@ _928 TILs and counting..._ - [Or Operator Precedence](ruby/or-operator-precedence.md) - [Override The Initial Sequence Value](ruby/override-the-initial-sequence-value.md) - [Parallel Bundle Install](ruby/parallel-bundle-install.md) +- [Parsing A CSV With Quotes In The Data](ruby/parsing-a-csv-with-quotes-in-the-data.md) - [Pass A Block To Count](ruby/pass-a-block-to-count.md) - [Passing Arbitrary Methods As Blocks](ruby/passing-arbitrary-methods-as-blocks.md) - [Passing Arguments To A Rake Task](ruby/passing-arguments-to-a-rake-task.md) diff --git a/ruby/parsing-a-csv-with-quotes-in-the-data.md b/ruby/parsing-a-csv-with-quotes-in-the-data.md new file mode 100644 index 0000000..af0ce88 --- /dev/null +++ b/ruby/parsing-a-csv-with-quotes-in-the-data.md @@ -0,0 +1,25 @@ +# Parsing A CSV With Quotes In The Data + +If a CSV contains unescaped quote characters--like you might find in a CSV full +of measurement data--then Ruby's +[CSV](https://ruby-doc.org/stdlib-2.6.1/libdoc/csv/rdoc/CSV.html) library will +be unable to parse it. + +Here is what happens with a line of CSV about some lumber: + +```ruby +> require 'csv' +> CSV.parse_line('oak,2",4"') +CSV::MalformedCSVError (Illegal quoting in line 1.) +``` + +However, we can enable some more lenient, liberal parsing of the data with the +`liberal_parsing` argument. + +```ruby +> require 'csv' +> CSV.parse_line('oak,2",4"', liberal_parsing: true) +=> ["oak", "2\"", "4\""] +``` + +[source](https://blog.bigbinary.com/2016/11/22/ruby-2-4-introduces-liberal_parsing-option-for-parsing-bad-csv-data.html)