为什么 Ruby 没有真正的 StringBuffer 或 StringIO? [英] Why doesn't Ruby have a real StringBuffer or StringIO?
问题描述
我最近读了一篇不错的帖子 在 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
bar"
# => really is ''`
Ruby 确实需要一个 StringBuffer,就像 Java 那样.StringBuffers 有两个重要目的.首先,它们让您测试 Ruby 的 StringIO 所做的一半的输出.其次,它们对于从小部件构建长弦很有用——乔尔一遍又一遍地提醒我们,否则非常非常慢.
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.
有好的替代品吗?
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#string
,不是 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!