Section 2.23. Parsing Comma-Separated Data

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 =,4,5)   # The numbers are 3, 4, and 5 s2 =,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   # 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.

The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: