Home

String#to_file: the easiest way to write a string to a file in Ruby

The Ruby file API has always struck me as inelegant (i.e., I’m constantly looking up its syntax). So I wrote String#to_file to make the common operation of writing a string to a file easy:

class String
  def to_file(filename)
    File.open(filename, 'w') {|f| f.write self }
  end
end

Now when you do this:

"some string".to_file("testing.txt")

You’ll get a file called “testing.txt” that contains “some string”. Easy, no?

You can use the same method to download files:

require 'open-uri'
url = 'http://blog.stackoverflow.com/audio/stackoverflow-podcast-001.mp3'
open(url).read.to_file(url.split('/').last)

And boom, you’ve downloaded the file to “stackoverflow-podcast-001.mp3”

Posted November 18th, 2010