String Interpolation in Ruby
Explore the concept of string interpolation in Ruby to improve program readability. Understand how to evaluate expressions within strings, handle input with newline characters, and use methods like chomp to clean input data. This lesson also compares Ruby's interpolation to JavaScript to deepen your understanding.
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, ...