Sep 29
A lot of developers know the dangers of concatenation with Strings and objects. In Java we had the StringBuffer.append vs. + (and now StringBuilder) knowledge transfer.
Ruby has the same issue, and people have talked about it before.
We ran into this issue in one of our projects, and I remember Dave Thomas talk about a problem that was fixed by moving from string concatenation to putting the contents on an array.
I think this benchmark says it all:
require 'benchmark'
Benchmark.bm do |x|
x.report do
a = 'foo'
100000.times { a += ' foo' }
end
x.report do
a = 'foo'
100000.times { a << ' foo' }
end
end
Output
dion@stewart [~]$ ruby t.rb user system total real 13.790000 25.180000 38.970000 ( 40.102451) 0.060000 0.000000 0.060000 ( 0.064342)
So, favour << unless you really want to copy strings around.

September 29th, 2006 at 2:32 pm
I’m not really sure this is an “issue”. You need both behaviors or someone will scream.
This is pretty old news, btw.
- Dan
September 29th, 2006 at 3:05 pm
You definitely do need both.
I also know this is old, but a lot of new ruby programmers have been caught on this one recently.
It is much more intuitive to do “foo” + “bar” for many new rubyists, and they do not know the downside (until it hits them).
Dion
October 2nd, 2006 at 12:06 pm
Java also tries to help you out by converting chains of + concats to StringBuilder under the hoods when compiling. Doesn’t help the looping example you have above, but works on stuff like:
String s = “foo” + s1 + “bar” + s2 + “baz” + s3;
This creates the same number and type of Objects as:
StringBuilder sb = new StringBuilder();
sb.append(”foo”).append(s1).append(”bar”).append(s2).append(”baz”).append(s3);
String s = sb.toString();