String concatenation
The +
method and interpolation create a new String. On the other hand, the <<
method directly modifies the instance of the variable a
. In Ruby, Strings are not immutable ⚠️.
With more than 3 concatenations (and even 2!), always prefer interpolation to the +
method:
+
can only be used to concatenate Strings, while interpolation implicitly calls theto_s
method.- A String is created for each call to
+
, while interpolation creates only one.
The <<
method is preferable to +=
if the original instance can be modified. It can also take an integer as argument, which will be converted to a String via the codepoint.
If you need to concatenate several arguments or even prefix, Ruby has thought of everything, almost! The implementation of concat
is the same as <<
, also allowing an integer. This is not the case with prepend
, which only accepts Strings and doesn’t have the equivalent >>
operator.