2.21. Embedding Expressions Within Strings

The #{} notation makes this easy. We need not worry about converting, appending, and concatenating; we can interpolate a variable value or other expression at any point in a string:

puts "#{temp_f} Fahrenheit is #{temp_c} Celsius"
puts "The discriminant has the value #{b*b - 4*a*c}."
puts "#{word} is #{word.reverse} spelled backward."

Bear in mind that full statements can also be used inside the braces. The last evaluated expression will be the one returned.

str = "The answer is #{ def factorial(n)
                          n==0 ? 1 : n*factorial(n-1)
                        end

                        answer = factorial(3) * 7}, of course."
# The answer is 42, of course.

There are some shortcuts for global, class, and instance variables, in which case the braces can be dispensed ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.