title: Ruby (Rails) unescape a string -- undo Array.to_s
body: <p>Have been hacking together a couple of libraries, and had an issue where a string was getting 'double escaped'.  </p>
  
  <p>for example:
  <strong>Fixed example</strong></p>
  
  <pre><code> &gt; x = ['a']
   =&gt; ["a"] 
   &gt; x.to_s
   =&gt; "[\"a\"]" 
   &gt; 
  </code></pre>
  
  <p>Then again to</p>
  
  <pre><code>\"\[\\\"s\\\"\]\"
  </code></pre>
  
  <p>This was happening while dealing with http headers.  I have a header which will be an array, but the http library is doing it's own character escaping on the array.to_s value.</p>
  
  <p>The workaround I found, was to convert the array to a string myself, and then 'undo' the to_s.  Like so:
  formatted_value = value.to_s</p>
  
  <pre><code>if value.instance_of?(Array)
    formatted_value = formatted_value.gsub(/\\/,"") #remove backslash                                                 
    formatted_value = formatted_value.gsub(/"/,"")  #remove single quote
    formatted_value = formatted_value.gsub(/\[/,"") #remove [                                                                                                     
    formatted_value = formatted_value.gsub(/\]/,"") #remove ]   
  end
  value = formatted_value
  </code></pre>
  
  <p>... There's gotta be a better way ... (without needing to monkey-patch the gems I'm using).  (yeah, this break's if my string actually contains those strings.)</p>
  
  <p>Suggestions?</p>
  
  <p>** UPDATE 2 **</p>
  
  <p>Okay.  Still having troubles in this neighborhood, but now I think I've figured out the core issue.  It's serializing my array to json after a to_s call.  At least, that seems to be reproducing what I'm seeing.</p>
  
  <p>['a'].to_s.to_json</p>
  
  <p>I'm calling a method in a gem that is returning the results of a to_s, and then I'm calling to_json on it.   </p>