StringIO is a Ruby standard-library class that lets a string behave like an IO object. Its instances support operations such as seeking, rewinding, and reading characters, so code written for open streams can also process in-memory data. section 12.0 section 12.5
The main design benefit is substitutability: a method can accept an IO-style input and output without caring whether they represent real files or strings. That keeps tests local and avoids creating, writing, and rereading temporary files. section 12.5.3
Testing a file transformation in memory
Create an input StringIO from a heredoc, an empty output StringIO, and pass both to a method that removes comment lines. Compare outfile.string with the expected result instead of managing actual files. section 12.5.3
module DeCommenter
def self.decomment(infile, outfile, comment_re = /\A\s*#/)
infile.each do |inline|
outfile.print inline unless inline =~ comment_re
end
end
end
This listing shows the reusable IO-oriented method that makes StringIO useful: it reads from one stream and prints accepted lines to another. section 12.5.3
StringIO also fits Ruby’s broader object-oriented treatment of input and output, where streams and file handles are objects. Related standard-library facilities include Tempfile for tests involving real files and open-uri, whose network reads return a StringIO object. section 12.0 section 12.5.4
