concatenate - to link together in a series or chain 1

interpolate - to insert between other things or parts 2

The words are big, but the concepts are simple. Both string concatenation and string interpolation are methods of building strings out of other strings. Of course, when there’s more than one way of doing the same thing, you should always find out which method is best suited for your particular use case.

In this blog, we’ll look at how concatenation differs from interpolation in Ruby. We’ll also go over some example use cases. At the end of the blog, you’ll be able to explain the difference, and choose the proper tool for your string building job.

String Concatenation

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).

String Interpolation

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"

Summary

So, let’s summarize the differences one last time:

  • 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.
  • You can see some benchmarking of this at this other post.

Basically, you want to use concatenation if you’re only dealing with two strings, and you’re never going to have to add a third.

If you have more than two strings to slap together, or think you may eventually, just use interpolation and save yourself the hassle of slower performance and manually adding .to_s to all of your concatenated to components.

Footnotes