...

/

String Interpolation in Ruby

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
Press + to interact
# String Interpolation Example code
puts "Your age?"
age = gets.to_i # Get age as input from user
age_months = age * 12 # Multiply age with 12 to convert into months
puts "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:

Press + to interact
# String Interploation Example code
puts "Your age?"
age = gets.to_i # Get age as input from user
puts "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 ...