问题描述
我最近阅读了一篇很好的在Ruby中使用 StringIO
。但是,作者没有提到的是 StringIO
只是一个我。没有O。你不能这样做,例如:
I recently read a nice post on using StringIO
in Ruby. What the author doesn't mention, though, is that StringIO
is just an "I." There's no "O." You can't do this, for example:
s = StringIO.new
s << 'foo'
s << 'bar'
s.to_s
# => should be "foo\nbar"
# => really is ''`
Ruby真的需要一个像Java一样的StringBuffer。 StringBuffers有两个重要用途。首先,它们让您测试Ruby的StringIO所做的输出的一半。其次,它们可用于从小部件构建长弦 - 这一点Joel一次又一次地提醒我们,否则非常慢。
Ruby really needs a StringBuffer just like the one Java has. StringBuffers serve two important purposes. First, they let you test the output half of what Ruby's StringIO does. Second, they are useful for building up long strings from small parts -- something that Joel reminds us over and over again is otherwise very very slow.
是否有一个好的替代品?
Is there a good replacement?
Ruby中的字符串确实是可变的,但这并不意味着我们应该始终依赖于该功能。如果 stuff
很大,那么这个的性能和内存要求非常糟糕。
It's true that Strings in Ruby are mutable, but that doesn't mean we should always rely on that functionality. If stuff
is large, the performance and memory requirements of this, for example, is really bad.
result = stuff.map(&:to_s).join(' ')
在Java中执行此操作的正确方法是:
The "correct" way to do this in Java is:
result = StringBuffer.new("")
for(String s : stuff) {
result.append(s);
}
虽然我的Java有点生疏。
Though my Java is a bit rusty.
推荐答案
我查看了 StringIO
的ruby文档,看起来你想要的是,而不是 StringIO#to_s
I looked at the ruby documentation for StringIO
, and it looks like what you want is StringIO#string
, not StringIO#to_s
因此,请将代码更改为:
Thus, change your code to:
s = StringIO.new
s << 'foo'
s << 'bar'
s.string
这篇关于为什么Ruby没有真正的StringBuffer或StringIO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!