Ruby: eval with string interpolation

Alexander.Iljushkin picture Alexander.Iljushkin · Jun 18, 2013 · Viewed 18.3k times · Source

I don't understand, why eval works like this:

"123 #{456.to_s} 789" # => "123 456 789"
eval('123 #{456.to_s} 789') # => 123

How can I interpolate into a string inside eval?

Update:

Thank you, friends. It worked.

So if you have a string variable with #{} that you want to eval later, you should do it as explained below:

string = '123 #{456} 789' 
eval("\"" + string + "\"")
# => 123 456 789

or

string = '123 #{456} 789' 
eval('"' + string + '"')
# => 123 456 789

Answer

AJcodez picture AJcodez · Jun 18, 2013

What's happening, is eval is evaluating the string as source code. When you use double quotes, the string is interpolated

eval '"123 #{456.to_s} 789"'
# => "123 456 789"

However when you use single quotes, there is no interpolation, hence the # starts a comment, and you get

123 #{456.to_s} 789
# => 123

The string interpolation happens before the eval call because it is the parameter to the method.

Also note the 456.to_s is unnecessary, you can just do #{456}.