Are strings mutable in Ruby?

前端 未结 3 1124
我在风中等你
我在风中等你 2020-12-03 09:55

Are Strings mutable in Ruby? According to the documentation doing

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

creates a new string object with

3条回答
  •  长情又很酷
    2020-12-03 10:37

    Just to complement, one implication of this mutability is seem below:

    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" 
    

    and

    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" 
    

    So, you should choose wisely the methods you use with strings in order to avoid unexpected behavior.

    Also, if you want something immutable and unique throughout your application you should go with symbols:

    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 
    

提交回复
热议问题