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!"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With