String Interpolation in Ruby
Learn about string interpolation in Ruby through the use of interactive code examples.
We'll cover the following...
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
ageas 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
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:
There are only 3 lines of code! There is no need for an extra variable, ...