Jun 03 2008

Using a String as a File in Ruby

Published by john at 7:37 am under Ruby

  
  

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"))

Technorati Tags: , ,

3 Responses to “Using a String as a File in Ruby”

  1. Thom Parkinon 04 Jun 2008 at 2:38 pm

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

  2. James Branamon 11 Jun 2008 at 6:26 am

    Hi John,

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

    –James

  3. johnon 11 Jun 2008 at 6:31 am

    James, go for it :)

Trackback URI | Comments RSS

Leave a Reply