The words are big, but the concepts are simple. 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 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 to interpolate strings in Ruby:

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

You can put any Ruby expression inside the #{} and you can have any number of them within the string.

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, so numbers and strings are both valid. Ruby can’t assume you want strings. 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.