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" binding ...

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.