0021 String_concatenation

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 ⚠️.

0021-string_concatenation_1.png

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 the to_s method.
  • A String is created for each call to +, while interpolation creates only one.

0021-string_concatenation_2.png

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.

0021-string_concatenation_3.png

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.

0021-string_concatenation_4.png

Links to Ruby documentation for <<, concat and prepend.