質問

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?

役に立ちましたか?

解決

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

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top