Ruby中的字符串是否可变?

Aly*_*Aly 33 ruby string mutable immutability

字符串在Ruby中是否可变?根据文件

str = "hello"
str = str + " world"
Run Code Online (Sandbox Code Playgroud)

使用值创建一个新的字符串对象,"hello world"但是当我们这样做时

str = "hello"
str << " world"
Run Code Online (Sandbox Code Playgroud)

它没有提到它创建了一个新对象,它是否会改变str对象,现在它将具有值"hello world"

Dog*_*ert 68

是的,<<改变同一个对象,并+创建一个新对象.示范:

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>
Run Code Online (Sandbox Code Playgroud)

  • +1用于演示如何确定对象是否确实相同或不同 (4认同)

Pab*_* B. 8

只是为了补充,这种可变性的一个含义如下:

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" 
Run Code Online (Sandbox Code Playgroud)

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" 
Run Code Online (Sandbox Code Playgroud)

因此,您应该明智地选择使用字符串的方法,以避免意外行为.

此外,如果您想在整个应用程序中使用不可变且唯一的东西,则应使用符号:

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 
Run Code Online (Sandbox Code Playgroud)