title: How do I force one field in Ruby's CSV output to be wrapped with double-quotes?
body: <p>I'm generating some CSV output using Ruby's built-in CSV. Everything works fine, but the customer wants the name field in the output to have wrapping double-quotes so the output looks like the input file. For instance, the input looks something like this:</p>
  <pre><code>1,1.1.1.1,&quot;Firstname Lastname&quot;,more,fields
  2,2.2.2.2,&quot;Firstname Lastname, Jr.&quot;,more,fields
  </code></pre>
  <p>CSV's output, which is correct, looks like:</p>
  <pre><code>1,1.1.1.1,Firstname Lastname,more,fields
  2,2.2.2.2,&quot;Firstname Lastname, Jr.&quot;,more,fields
  </code></pre>
  <p>I know CSV is doing the right thing by not double-quoting the third field just because it has embedded blanks, and wrapping the field with double-quotes when it has the embedded comma. What I'd like to do, to help the customer feel warm and fuzzy, is tell CSV to always double-quote the third field.</p>
  <p>I tried wrapping the field in double-quotes in my <code>to_a</code> method, which creates a <code>&quot;Firstname Lastname&quot;</code> field being passed to CSV, but CSV laughed at my puny-human attempt and output <code>&quot;&quot;&quot;Firstname Lastname&quot;&quot;&quot;</code>. That is the correct thing to do because it's escaping the double-quotes, so that didn't work.</p>
  <p>Then I tried setting CSV's <code>:force_quotes =&gt; true</code> in the <code>open</code> method, which output double-quotes wrapping all fields as expected, but the customer didn't like that, which I expected also. So, that didn't work either.</p>
  <p>I've looked through the Table and Row docs and nothing appeared to give me access to the &quot;generate a String field&quot; method, or a way to set a &quot;for field n always use quoting&quot; flag.</p>
  <p>I'm about to dive into the source to see if there's some super-secret tweaks, or if there's a way to monkey-patch CSV and bend it to do my will, but wondered if anyone had some special knowledge or had run into this before.</p>
  <p>And, yes, I know I could roll my own CSV output, but I prefer to not reinvent well-tested wheels. And, I'm also aware of FasterCSV; That's now part of Ruby 1.9.2, which I'm using, so explicitly using FasterCSV buys me nothing special. Also, I'm not using Rails and have no intention of rewriting it in Rails, so unless you have a cute way of implementing it using a small subset of Rails, don't bother. I'll downvote any recommendations to use any of those ways just because you didn't bother to read this far.</p>