25 June, 2008

Ruby Needs a StringBuffer

john has written a little post about using a String as a File (really as an IO) in Ruby. He does a great job explaining how StringIOs work for reading characters. They're particularly good for unit tests on IO operations.

What john doesn't mention, however, is that StringIO is only an 'I.' It has 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 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.

So I wrote a StringBuffer, but it's not very good, and it's not very fast. What we need is one written in C in the core Ruby library. Now that will help Rails scale.