I am attempting to write a simple function to perform string interpolation on arbitrary text in ruby. I also want the function to not evaluate escaped interpolation blocks so that "\#{foo}" would be converted to "#{foo}" rather than evaluated.
When I pass an expression with an escaped block, the value appears correct when I use the puts
method, but includes the escape character when I use p
. I don't understand why.
Here is my code:
def evil_mark text
part = text.partition(/[^\\]\#{.*?}/)
return_string = part[0]
until part[1] == ""
return_string << eval("\"" + part[1] + "\"")
part = evil_mark(part[2]).partition(/[^\\]\#{.*?}/)
return_string << part[0]
end
return_string.gsub!(/\\\#{.*?}/){|s| s[1..-1]}
return return_string
end
$foo = 'faz'
$bar = 'baz'
s = 'This is some \#{$foo} bar and some #{$bar} bat'
puts evil_mark s
#~> This is some #{$foo} bar and some baz bat
p evil_mark s
#~> "This is some \#{$foo} bar and some baz bat"
By the way, I understand that it can be dangerous to use the eval
method.