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.
String Concatenation and String Appending You can concatenate in any order, such as concatenating str1 between str2 and str3 . Appending strings refers to appending one or more strings to the end of another string. In some cases, these terms are absolutely interchangeable.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With