Are strings in Ruby mutable? [duplicate]

寵の児 提交于 2019-11-28 06:15:17

Yes, strings in Ruby, unlike in Python, are mutable.

s += "hello" is not appending "hello" to s - an entirely new string object gets created. To append to a string 'in place', use <<, like in:

s = "hello"
s << "   world"
s # hello world
ruby-1.9.3-p0 :026 > s="foo"
 => "foo" 
ruby-1.9.3-p0 :027 > s.object_id
 => 70120944881780 
ruby-1.9.3-p0 :028 > s<<"bar"
 => "foobar" 
ruby-1.9.3-p0 :029 > s.object_id
 => 70120944881780 
ruby-1.9.3-p0 :031 > s+="xxx"
 => "foobarxxx" 
ruby-1.9.3-p0 :032 > s.object_id
 => 70120961479860 

so, Strings are mutable, but += operator creates a new String. << keeps old

Appending in Ruby String is not +=, it is <<

So if you change += to << your question gets addressed by itself

Strings in Ruby are mutable, but you can change it with freezing.

irb(main):001:0> s = "foo".freeze
=> "foo"
irb(main):002:0> s << "bar"
RuntimeError: can't modify frozen String

Ruby Strings are mutable. But you need to use << for concatenation rather than +.
In fact concatenating string with
+ operator(immutable) because it creates new string object.
<< operator(mutable) because it changes in the same object.

From what I can make of this pull request, it will become possible in Ruby 3.0 to add a "magic comment" that will make all string immutable, rather than mutable.

Because it seems you have to explicitly add this comment, it seems like the answer to "are string mutable by default?" will still be yes, but a sort of conditional yes - depends on whether you wrote the magic comment into your script or not.

EDIT

I was pointed to this bug/issue on Ruby-Lang.org that definitively states that some type of strings in Ruby 3.0 will in fact be immutable by default.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!