Ruby中的字符串是否可变?

时间:2011-04-16 12:53:15

标签: ruby string immutability mutable

Ruby中的字符串是否可变?根据{{​​3}}做的

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

创建一个值为"hello world"的新字符串对象,但是当我们执行

str = "hello"
str << " world"

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

3 个答案:

答案 0 :(得分:65)

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

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>

答案 1 :(得分:7)

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

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 

答案 2 :(得分:-1)

是的,他们是:

x = "hallo"
x[1] = "e"

p x # "hello"