Home > Articles > Programming > Ruby

📄 Contents

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

2.22 Delayed Interpolation of Strings

Sometimes we might want to delay the interpolation of values into a string. There is no perfect way to do this. One way is to use a block:

str = proc {|x,y,z| "The numbers are #{x}, #{y}, and #{z}" }

s1 = str.call(3,4,5)   # The numbers are 3, 4, and 5
s2 = str.call(7,8,9)   # The numbers are 7, 8, and 9

A more heavyweight solution is to store a single-quoted string, wrap it in double quotes, and evaluate it:

str = '#{name} is my name, and #{nation} is my nation'
name, nation = "Stephen Dedalus", "Ireland"
s1  = eval('"' + str + '"')
# Stephen Dedalus is my name, and Ireland is my nation.

It's also possible to pass in a different binding to eval:

bind = proc do
  name,nation = "Gulliver Foyle", "Terra"
end.call   # Contrived example; returns binding of block's context
s2 = eval('"' + str + '"',bind)
# Gulliver Foyle is my name, and Terra is my nation.

The eval technique may naturally have some "gotchas" associated with it. For example, be careful with escape sequences such as \n for newline.

  • + Share This
  • 🔖 Save To Your Account