Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to an existing string

Tags:

ruby

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.

like image 861
Neeraj Singh Avatar asked Mar 01 '10 15:03

Neeraj Singh


People also ask

Can append be used in string?

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.

How do you add strings to a string?

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.


1 Answers

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 
like image 113
sepp2k Avatar answered Sep 28 '22 22:09

sepp2k