Ruby中的字符串是否可变?

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

str = "hello" str = str + " world" 

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

 str = "hello" str << " world" 

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

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

 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> 

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

 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" 

 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" 

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

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

 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