Using a String as a File in Ruby

by John Muchow

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"))
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo