13

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
3
  • 1
    What do you mean by "macro substitutions"? Commented Jun 18, 2013 at 13:14
  • @sawa, i meant #{} sections, please , edit it in right way, I just don't know how to say it on english Commented Jun 18, 2013 at 13:45
  • 1
    Okay, maybe you meant interpolation. Commented Jun 18, 2013 at 13:47

2 Answers 2

24

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}.

Sign up to request clarification or add additional context in comments.

2 Comments

Replacing the single quotes with double quotes gives a syntax error because eval("123 #{456.to_s} 789") is evaluated as 123 456 789
what if the string has #{} and quotes like this: string = '12 #{45} 78 "9" 0'
5

You wanted:

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

. . . hopefully you can see why?

The code passed to the interpretter from eval is exactly as if you had written it (into irb, or as part of a .rb file), so if you want an eval to output a string value, the string you evaluate must include the quotes that make the expression inside it a String.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.