Delayed substitution of Ruby strings
Today at work I faced an interesting problem I didn't know immediately how to solve: how do you delay substitution in Ruby strings? That is, I wanted to declare a string like s="delayed substitution:#{i}" and not have #{i} evaluated until later. The difference between declaring a string with single or double quotes is the solution:
irb(main):001:0> s='delayed substitution of i:#{i}'
=> "delayed substitution of i:\#{i}"
irb(main):002:0> i=42
=> 42
irb(main):003:0> eval('"' + s + '"')
=> "delayed substitution of i:42"
irb(main):004:0>
Here #{i} is not evaluated until between doubles quotes.
Sweet!
0 Comments:
Post a Comment
<< Home