In this guide, we will discuss how to interpolate strings in the Ruby programming language.
Using + Operator
The easiest way to interpolate values in a literal string is to use the addition operator. Consider the example shown below:
puts "Hello " + name
In the example above, we declare a variable called name. It holds the value “Alice”. Using the addition operator, we interpolate it into a string value.
The Ruby interpreter will fetch the value referenced by the variable name and use it as the actual value. The resulting output is as shown:
Hello Alice
The addition operator contains a drawback when interpolating variables into a string. It only works with strings objects.
Take the example below:
puts "I am " + age + " years old"
If you try to execute such an operation, Ruby will return a TypeError
`+’: no implicit conversion of nil into String (TypeError)
One way to resolve such an issue is to convert the variable into a string using the to_s method.
For example:
puts ("I am " + age.to_s + " years old")
Now we can inject the integer variable into the string by casting it as a string.
Using the << Operator
The left shift operator works similarly to the addition operator. It injects the passed variable into a string literal.
Example:
puts lang << " is an fun!"
Similar to the addition operator, you have to convert the variable to a string to prevent TypeErrors.
Using #{}
The two methods we discussed above hold a single drawback; it gets complicated to perform an expression inside a string literal.
Take a look at the example below:
puts "The area of the cirlcle of radius " + radius.to_s + " is " + radius * radius * 3.141 + " cm2"
The above operation is not possible using the methods we discussed above.
To resolve this, we can use the expression substitution operator in Ruby:
The syntax is as:
We put the variable or expression inside the pair of curly braces. Ruby will evaluate the expression and interpolate to the string.
Consider the previous example using the interpolation operator.
puts "The area of the cirlcle of radius #{radius} is #{radius * radius * 3.141} cm2"
That is much better. Using the above notation, we can inject a single variable and valid ruby expressions inside a string.
Below is the resulting output:
The area of the cirlcle of radius 7.43 is 173.3985909 cm2
In this case, we do not have to perform the expression, convert it to a string, and then interpolate it to the string.
Using this method, Ruby will take care of everything.
Conclusion
This guide has illustrated how to work with string interpolation in the Ruby language using features such as the addition operator, left shift, and the expression substitution operator.