Appending to an existing string

Ruby

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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 - Ruby

you can also use the following:

s.concat("world")

Solution 3 - Ruby

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 - Ruby

Yet an other way:

s.insert(-1, ' world')

Solution 5 - Ruby

Here's another way:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNeeraj SinghView Question on Stackoverflow
Solution 1 - Rubysepp2kView Answer on Stackoverflow
Solution 2 - RubyJu NogueiraView Answer on Stackoverflow
Solution 3 - RubyShadowfirebirdView Answer on Stackoverflow
Solution 4 - RubybharathView Answer on Stackoverflow
Solution 5 - RubychuckSaldanaView Answer on Stackoverflow