tags:

views:

170

answers:

1

I see a lot of this sort of this going on in Ruby:

myString = "Hello " << "there!"

How is this different from doing

myString = "Hello " + "there!"
+23  A: 

In Ruby, strings are mutable. That is, a string value can actually be changed, not just replaced with another object. x << y will actually add the string y to x, while x + y will create a new String and return that.

This can be tested simply in the ruby interpreter:

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"

Notably, see that x + "there" returned "hellotherethere" but the value of x was unchanged. Be careful with mutable strings, they can come and bite you. Most other managed languages do not have mutable strings.

Note also that many of the methods on String have both destructive and non-destructive versions: x.upcase will return a new string containing the upper-case version of x, while leaving x alone; x.upcase! will return the uppercased value -and- modify the object pointed to by x.

Crast
An excellent explanation. x = "Many"; x << " thanks!"
Mongus Pong
BTW: This also applies to most other collection-ish objects in Ruby. `Array#<<` is appending by mutating, `Array#+` is appending by creating a new Array. `Set#<<` is adding an element to the set, `Set#+` is set union. And so on.
Jörg W Mittag