【问题标题】:Are strings mutable in Ruby?Ruby 中的字符串是可变的吗?
【发布时间】:2011-08-06 21:29:35
【问题描述】:

Ruby 中的字符串是可变的吗?根据documentation做的

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

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

str = "hello"
str << " world"

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

【问题讨论】:

    标签: ruby string immutability mutable


    【解决方案1】:

    是的,&lt;&lt; 改变了同一个对象,+ 创建了一个新对象。示范:

    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 用于演示如何确定对象是否确实相同或不同
    【解决方案2】:

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

    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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      相关资源
      最近更新 更多