When appending to a string in Ruby use the << method instead of +=
If you come from another language, you might be tempted to use the += operator when appending to a string.
- my_str = “Marco ”
- my_str += “Polo”
It works… but there is a better way to do it : the « method.
- my_str = “Marco ”
- my_str « “Polo”
#UPDATE
I have removed my initial claim about operator precedence as it isn’t really accurate. There is a much better reason to use « instead of += when appending to a string… something I didn’t even realize (Thanks to Gregory). += will create a new String instance and will assign it to your left object. On the other hand, « will append the new string directly into your already existing left object. One could argue that += is only different than « and not better, but to me « is what you’ll want to use 99% of the time (if not 100%) when appending to a String. I have yet to see a real case where one would want to “lose” it’s existing String instance just to get a new one containing the exact same value.
You can also use the « method with arrays :
- [1,2,3] « 4 #gives [1,2,3,4]
Be careful however when using « with Fixnum/Bignum instances. With these objects, the « method will shift the bits of your integer to the left. If you want to do a summation (append style that is), you will have to use +=