Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: eval with string interpolation

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
like image 702
Alexander.Iljushkin Avatar asked Jun 18 '13 13:06

Alexander.Iljushkin


People also ask

How do you interpolate a string in Ruby?

Using String Interpolation "My name is " + my_name + "!" You can do this: "My name is #{my_name}!" Instead of terminating the string and using the + operator, you enclose the variable with the #{} syntax.

What does #{} do in Ruby?

You use it to represent a variable you want to print or puts out. For example: puts "#{var}" would puts out the value stored within your variable var .

What is %{} in ruby?

This is percent sign notation. The percent sign indicates that the next character is a literal delimiter, and you can use any (non alphanumeric) one you want. For example: %{stuff} %[stuff] %?


2 Answers

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.

like image 186
Neil Slater Avatar answered Oct 16 '22 09:10

Neil Slater


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

like image 40
AJcodez Avatar answered Oct 16 '22 11:10

AJcodez