Using a String as a File in Ruby

Tue, Jun 3

The ability to treat a string as a file can often be quite handy. Generally this most useful when classes/methods expect a file object as an input type. With Ruby, you can use the StringIO library to use a string when a file is expected, thus allowing operations such as read, write, rewind, etc.

In the lines below, the code after the #=> shows the results when executing the script. Follow the code to see several examples of a string using operations that are typically reserved for files.

require 'stringio'
str = StringIO.new %{This is a test of a string as a file. \r\n
                     And this could be another line in the file}

# Get a line
str.gets # => "This is a test of a string as a file. \r\n"

# Get the next 18 charaters
str.read(18) # => " And this could be"

# Seek to new position and read 7 more characters
str.pos = 59  # => 59
str.read(7) # => "another"

# Rewind the file and overwrite some of the existing text
str.rewind
str.write("Here's how to use")

# Rewind again and output the new contents
str.rewind
str.read # => "Here's how to use a string as a file.
     \r\n And this could be another line in the file"
str.eof? # => true

Any easy way to work with a string in a method that is expecting a file is to create a new StringIO object and pass the result to the method requiring a file type. For example:

  some_method(StringIO.new("Your string here"))

3 comments

That is absolutely brilliant! And just one more reason I love Ruby.

by Thom Parkin on Jun 4, 2008. Reply #

Hi John,

This would make a great Tips & Tricks entry for NB Community Docs. Can we use it?

–James

by James Branam on Jun 11, 2008. Reply #

James, go for it :)

by john on Jun 11, 2008. Reply #

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>