Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does << differ from +?

Tags:

ruby

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!"
like image 512
Mongus Pong Avatar asked Jan 16 '10 01:01

Mongus Pong


1 Answers

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.

like image 121
Crast Avatar answered Oct 04 '22 15:10

Crast