title: Read binary file as string in Ruby
body: <p>I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this:</p>
  
  <pre><code>file = File.open("path-to-file.tar.gz")
  contents = ""
  file.each {|line|
    contents &lt;&lt; line
  }
  </code></pre>
  
  <p>I thought that would be enough to convert it to a string, but then when I try to write it back out like this...</p>
  
  <pre><code>newFile = File.open("test.tar.gz", "w")
  newFile.write(contents)
  </code></pre>
  
  <p>It isn't the same file. Doing <code>ls -l</code> shows the files are of different sizes, although they are pretty close (and opening the file reveals most of the contents intact). Is there a small mistake I'm making or an entirely different (but workable) way to accomplish this?</p>