2011-04-16 36 views
27

在Ruby中字符串是否可变?按照documentationRuby中的字符串是否可变?

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

创造与价值"hello world"一个新的字符串对象,但是当我们做

str = "hello" 
str << " world" 

它没有提到它创建一个新的对象,所以它发生变异的str对象,现在它的值是"hello world"

回答

62

是的,<<突变相同的对象,+创建一个新的。演示:

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> 
+3

+1用于演示如何确定对象确实是相同或不同 – Cumbayah 2012-12-14 14:18:41

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 
相关问题