与 String 相比,在 Ruby 中使用 StringIO 有哪些优势?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12592234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the advantages to using StringIO in Ruby as opposed to String?
提问by Scott Joseph
When is it considered proper to use Ruby's StringIO as opposed to just using String?
什么时候使用 Ruby 的 StringIO 而不是只使用 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?
我想我理解它们之间的根本区别,正如“什么是 ruby 的 StringIO 类到底是什么?”所强调的那样,StringIO 使人们能够以面向流的方式读取和写入字符串。但这实际上意味着什么?
What is a good example of a practical use for using StringIO when simply using String wouldn't really cut it?
当简单地使用 String 并不能真正削减它时,使用 StringIO 的实际用途的一个很好的例子是什么?
回答by David Grayson
Basically, it makes a string look like an IO object, hence the name StringIO.
基本上,它使字符串看起来像一个 IO 对象,因此名称为 StringIO。
The StringIOclass has readand writemethods, 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.
该StringIO的类有read和write方法,因此它可以被传递给设计读取和文件或套接字写代码的部分。如果您有一个字符串,并且为了测试您的文件代码而希望它看起来像一个文件,那就太好了。
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
回答by Steve Benner
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:
我真的很喜欢 StringIO 用于逐行附加文本的用例,而不必"\n"一遍又一遍地使用。例如,而不是这样:
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.newbut regardless, make sure to keep in mind the actual string is accessed via the StringIO#stringmethod.
哪个更干净。没有必要使用 的块形式String.IO,您可以像这样创建一个对象:s = StringIO.new但无论如何,请务必记住通过该StringIO#string方法访问实际字符串。

