Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 486
Scott Joseph Avatar asked Sep 25 '12 22:09

Scott Joseph


People also ask

What is StringIO in Ruby?

Pseudo I/O on String object. Commonly used to simulate `$stdio` or `$stderr`

What is StringIO?

The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.


2 Answers

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 
like image 146
David Grayson Avatar answered Nov 09 '22 16:11

David Grayson


I really like StringIO for the use-case of appending text line-by-line without having to use "\n" over and over again. For example, instead of this:

s = '' s << "\n" << "some text on a new line" s << "\nthis is pretty awkward" s = "#{s}\neven more ugly!" 

I can do this

s = StringIO.open do |s|   s.puts 'adding newlines with puts is easy...'   s.puts 'and simple'   s.string end 

Which is much cleaner. It isn't necessary to use the block form of String.IO, you can create an object like so: s = StringIO.new but regardless, make sure to keep in mind the actual string is accessed via the StringIO#string method.

like image 27
Steve Benner Avatar answered Nov 09 '22 16:11

Steve Benner