string

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