Appending to an existing string

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.


Solution 1:

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

Solution 2:

you can also use the following:

s.concat("world")

Solution 3:

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.

Solution 4:

Yet an other way:

s.insert(-1, ' world')

Solution 5:

Here's another way:

fist_segment = "hello,"
second_segment = "world."
complete_string = "#{first_segment} #{second_segment}"