字符串在Ruby中可变吗? [英] Are strings mutable in Ruby?
本文介绍了字符串在Ruby中可变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
字符串在Ruby中可变吗?根据文档做
Are Strings mutable in Ruby? According to the documentation doing
str = "hello"
str = str + " world"
创建一个值为"hello world"
的新字符串对象,但是当我们这样做
creates a new string object with the value "hello world"
but when we do
str = "hello"
str << " world"
它没有提到它会创建一个新对象,所以它会突变str
对象,该对象现在将具有值"hello world"
?
It does not mention that it creates a new object, so does it mutate the str
object, which will now have the value "hello world"
?
推荐答案
是的,<<
对同一个对象进行了变异,并且+
创建了一个新对象.演示:
Yes, <<
mutates the same object, and +
creates a new one. Demonstration:
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中可变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文