tags:

views:

87

answers:

3

To append to an existing string this is what I am doing.

s = 'hello'
s.gsub!(/$/, ' world');

Is there a better way to append to an existing string.

Before someone suggests following answer lemme show that this one does not work

s = 'hello'
s.object_id
s = s + ' world'
s.object_id 

In the above case object_id will be different for two cases.

+11  A: 

You can use << to append to a string in-place.

s = "foo"
old_id = s.object_id
s << "bar"
s                      #=> "foobar"
s.object_id == old_id  #=> true
sepp2k
+6  A: 

you can also use the following:

s.concat("world")
j.
+2  A: 

Can I ask why this is important?

I know that this is not a direct answer to your question, but the fact that you are trying to preserve the object ID of a string might indicate that you should look again at what you are trying to do.

You might find, for instance, that relying on the object ID of a string will lead to bugs that are quite hard to track down.

Shadowfirebird
Maybe to modify parameters by reference? (which is probable bad design in a full-fledged oop language)
hurikhan77
Or just to avoid creating too many new objects? That's perfectly reasonable.
James A. Rosen
Surely if you modify a string in place and a new object is created, then the old object gets garbage collected? Should we really be worrying about the number of String objects we create?
Shadowfirebird