String Interpolation in Ruby
Learn about string interpolation in Ruby through the use of interactive code examples.
String interpolation
We can significantly improve the readability of a program if we take advantage of string interpolation:
Note: To run the program below, we give our
age
as input using STDIN, or we can also execute this program in the terminal at the end of the lesson using the command:
$ ruby string_interpolation_example_1.rb
# String Interpolation Example codeputs "Your age?"age = gets.to_i # Get age as input from userage_months = age * 12 # Multiply age with 12 to convert into monthsputs "Your age is #{age_months}" # string interpolation using curly brackets
Enter the input below
Explanation
There is no need for typecasting on line 6. Every object in Ruby can be converted to a string using the to_s
method. That’s why there is a common syntax for every type, and it’s called interpolation.
The trick is that the expression gets
is evaluated inside curly braces. We have a very simple expression inside curly braces, just age_months
, but it can be any Ruby code, such as 2 + 2
. And at the end, the final result will get converted to a string. Let’s look at another example:
# String Interploation Example codeputs "Your age?"age = gets.to_i # Get age as input from userputs "Your age is #{age * 12}" # string interpolation using curly brackets
Enter the input below
There are only 3 lines of code! There is no need for an extra variable, because ...