What are the advantages to using StringIO in Ruby as opposed to String?

Scott Joseph picture Scott Joseph · Sep 26, 2012 · Viewed 29.1k times · Source

When is it considered proper to use Ruby's StringIO as opposed to just using String?

I think I understand the fundamental difference between them as highlighted by "What is ruby's StringIO class really?", that StringIO enables one to read and write from/to a String in a stream-oriented manner. But what does this mean practically?

What is a good example of a practical use for using StringIO when simply using String wouldn't really cut it?

Answer

David Grayson picture David Grayson · Sep 26, 2012

Basically, it makes a string look like an IO object, hence the name StringIO.

The StringIO class has read and write methods, so it can be passed to parts of your code that were designed to read and write from files or sockets. It's nice if you have a string and you want it to look like a file for the purposes of testing your file code.

def foo_writer(file)
  file.write "foo"
end

def test_foo_writer
  s = StringIO.new
  foo_writer(s)
  raise "fail" unless s.string == "foo"
end