Join my Laravel for REST API's course on Udemy 👀

String interpolation in Ruby

August 6, 2022  ‐ 1 min read

To use string interpolation in Ruby we must use a double quoted string, in which we can interpolate variable using #{}. Such as:

you = 'Robot'
puts "Hey #{you}"
# => Hey Robot

String interpolation is a nice alternative to string concatenation.

In Ruby we can use the plus-sign (+) to do string concatenation. Which is basically glueing strings together as one. See for example:

name = 'Koen'
str = 'Hello ' + name
# => "Hello Koen"

Although this works fine, if you need to concatenate multiple strings this quickly can get a bit messy. See for example the following:

first_name = 'Koen'
last_name = 'Woortman'
str = 'Hello ' + first_name + ' ' + last_name + '!'
# => "Hello Koen Woortman!"

Obviously we can do the above a bit smarter, by combining the first and last name in one variable before doing string concatenation. But I hope you get the point.

Enter string interpolation, which is allowed in double quoted strings. Thus using "" instead of ''. To achieve the same as above with string interpolation see the following code example.

first_name = 'Koen'
last_name = 'Woortman'
str = "Hello #{first_name} #{last_name}!"
# => "Hello Koen Woortman!"