October 2006
Intermediate to advanced
888 pages
16h 55m
English
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 9A 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 ...
Read now
Unlock full access