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!"
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Ruby, strings are mutable. That is, a string value can actually be changed, not just replaced with another object.
x << ywill actually add the string y to x, whilex + ywill create a new String and return that.This can be tested simply in the ruby interpreter:
Notably, see that
x + "there"returned “hellotherethere” but the value ofxwas 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.upcasewill 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.