附加到现有字符串

为了给现有的字符串添加这些内容,我正在这样做。

s = 'hello'
s.gsub!(/$/, ' world');

是否有更好的方法将现有字符串附加到。

在有人建议下面的答案之前,让我证明这一个不工作

s = 'hello'
s.object_id
s = s + ' world'
s.object_id

在上述情况下,object _ id 在两种情况下是不同的。

137649 次浏览

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

you can also use the following:

s.concat("world")

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.

Yet an other way:

s.insert(-1, ' world')

Here's another way:

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