Ruby: eval with string interpolation
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}
.
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
.