Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

6.15. Pretending a String Is a File

Problem

You want to call code that expects to read from an open file object, but your source is a string in memory. Alternatively, you want to call code that writes its output to a file, but have it actually write to a string.

Solution

The StringIO class wraps a string in the interface of the IO class. You can treat it like a file, then get everything that's been "written" to it by calling its string method.

Here's a StringIO used as an input source:

	require 'stringio'
	s = StringIO.new %{I am the very model of a modern major general.
	I've information vegetable, animal, and mineral.}
	
	s.pos                                 # => 0
	s.each_line { |x| puts x }
	# I am the very model of a modern major general.
	# I've information vegetable, animal, and mineral.
	s.eof?                                # => true
	s.pos                                 # => 95
	s.rewind
	s.pos                                 # => 0
	s.grep /general/
	# => ["I am the very model of a modern major general.\n"]

Here are StringIO objects used as output sinks:

	s = StringIO.new
	s.write('Treat it like a file.')
	s.rewind
	s.write("Act like it's")
	s.string							 # => "Act like it's a file."
	
	require 'yaml'
	s = StringIO.new
	YAML.dump(['A list of', 3, :items], s)
	puts s.string
	# ---
	# - A list of
	# - 3
	# - :items

Discussion

The Adapter is a common design pattern: to make an object acceptable as input to a method, it's wrapped in another object that presents the appropriate interface. The StringIO class is an Adapter between String and File (or IO), designed for use with methods that work on File or IO instances. With a StringIO ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required