[ruby] 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.

This question is related to ruby

The answer is


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.


you can also use the following:

s.concat("world")

Yet an other way:

s.insert(-1, ' world')

Here's another way:

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