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 = %{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 # => " And this could be"

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

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

# Rewind again and output the new contents
str.rewind # => "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("Your string here"))


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

by Thom Parkin on Jun 4, 2008. #

Hi John,

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


by James Branam on Jun 11, 2008. #

James, go for it :)

by john on Jun 11, 2008. #