<<与+有何不同?

Mon*_*ong 15 ruby

我在Ruby中看到了很多这样的事情:

myString = "Hello " << "there!"
Run Code Online (Sandbox Code Playgroud)

这与做有什么不同

myString = "Hello " + "there!"
Run Code Online (Sandbox Code Playgroud)

Cra*_*ast 25

在Ruby中,字符串是可变的.也就是说,实际上可以更改字符串值,而不仅仅是替换为另一个对象. x << y实际上会将字符串y添加到x,同时x + y将创建一个新的String并返回该字符串.

这可以在ruby解释器中简单地测试:

irb(main):001:0> x = "hello"
=> "hello"
irb(main):002:0> x << "there"
=> "hellothere"
irb(main):003:0> x
=> "hellothere"
irb(main):004:0> x + "there"
=> "hellotherethere"
irb(main):005:0> x
=> "hellothere"
Run Code Online (Sandbox Code Playgroud)

值得注意的是,看到x + "there"返回"hellotherethere",但价值x没有变化.小心可变的字符串,他们可以来咬你.大多数其他托管语言没有可变字符串.

另请注意,String上的许多方法都具有破坏性和非破坏性版本:x.upcase将返回包含x的大写版本的新字符串,同时保留x; x.upcase!将返回大写的值 - 并 - 修改x指向的对象.

  • BTW:这也适用于Ruby中的大多数其他集合对象.`Array#<<`通过变异追加,'Array#+`通过创建一个新的Array来追加.`set#<<`是在集合中添加一个元素,`Set#+`是set union.等等. (4认同)