The words are big, but the concepts are simple, and both are methods of building strings out of other strings. We’ll jump into the examples and discuss both.

Let’s see how to concatenate two strings in Ruby:

username = "mrodrigues"
greeting = "Hello, " + username + "."
puts greeting #=> "Hello, mrodrigues."

As you can see, we just use the + operator to add the strings up. This is a bit messy, as we have to tack the period on at the end. We also have to make four strings (three components, and 1 concatenated).

There is another option though, let’s check out how string interpolation works in Ruby:

username = "mrodrigues"
greeting = "Hello, #{username}."
puts greeting #=> "Hello, mrodrigues."

Here, we just “interpolate” the variables within the string. This is great if we end up adding more variables later, as we won’t have to keep adding things on. You can put any Ruby expression inside the #{}.

Generally, you’ll want to stick with interpolation, as it’s quicker, and it automatically calls to_s on whatever you interpolate.

You should stick with concatenation if you need to avoid the above issue, as it does not automatically call to_s on each addend. This makes sense because the concatenation operator (+) is also the addition operator. When you’re using interpolation, it’s obvious you want a string. Just be sure that to_s is what you expect.

( 7 + 3 ) #=> 10

( 7.to_s + 3 ) #=> TypeError

( 7.to_s + 3.to_s ) #=> "73"

( "#{7}#{3}" ) #=> "73"

( "#{7 + 3}" ) #=> "10"

So, in summary:

  • Interpolation is faster, especially as you concatenate/interpolate more strings. This is because concatenation makes a new string for each + operation.
  • Interpolation calls to_s on each interpolated object automatically.
  • Interpolation requires double quotes.
  • Concatenation doesn’t change your object type to string automatically.
  • Concatenation is fine, and possibly faster, for simply adding 2 strings.