Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

2.21 Embedding Expressions within Strings

The #{} notation makes embedding expressions within strings 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)

                        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 with:

puts "$gvar = #$gvar and ivar = #@ivar."

Note that this technique is not applicable for single-quoted strings (because their contents are not expanded), but it does work for double-quoted here-documents and regular expressions.

  • + Share This
  • 🔖 Save To Your Account