Are strings mutable in Ruby?

送分小仙女□ 提交于 2019-11-27 14:17:20
Dogbert

Yes, << mutates the same object, and + creates a new one. Demonstration:

irb(main):011:0> str = "hello"
=> "hello"
irb(main):012:0> str.object_id
=> 22269036
irb(main):013:0> str << " world"
=> "hello world"
irb(main):014:0> str.object_id
=> 22269036
irb(main):015:0> str = str + " world"
=> "hello world world"
irb(main):016:0> str.object_id
=> 21462360
irb(main):017:0>

Just to complement, one implication of this mutability is seem below:

ruby-1.9.2-p0 :001 > str = "foo"
 => "foo" 
ruby-1.9.2-p0 :002 > ref = str
 => "foo" 
ruby-1.9.2-p0 :003 > str = str + "bar"
 => "foobar" 
ruby-1.9.2-p0 :004 > str
 => "foobar" 
ruby-1.9.2-p0 :005 > ref
 => "foo" 

and

ruby-1.9.2-p0 :001 > str = "foo"
 => "foo" 
ruby-1.9.2-p0 :002 > ref = str
 => "foo" 
ruby-1.9.2-p0 :003 > str << "bar"
 => "foobar" 
ruby-1.9.2-p0 :004 > str
 => "foobar" 
ruby-1.9.2-p0 :005 > ref
 => "foobar" 

So, you should choose wisely the methods you use with strings in order to avoid unexpected behavior.

Also, if you want something immutable and unique throughout your application you should go with symbols:

ruby-1.9.2-p0 :001 > "foo" == "foo"
 => true 
ruby-1.9.2-p0 :002 > "foo".object_id == "foo".object_id
 => false 
ruby-1.9.2-p0 :003 > :foo == :foo
 => true 
ruby-1.9.2-p0 :004 > :foo.object_id == :foo.object_id
 => true 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!