Ruby:带字符串插值的eval [英] Ruby: eval with string interpolation

查看:60
本文介绍了Ruby:带字符串插值的eval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白,为什么eval如此工作:

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

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

如何在eval内部插入字符串?

How can I interpolate into a string inside eval?

更新:

谢谢你,朋友们.有效.

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

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

推荐答案

发生了什么事,eval正在将字符串作为源代码进行评估.当您使用双引号时,字符串将被内插

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

字符串内插发生在eval调用之前,因为它是方法的参数.

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

还请注意,456.to_s是不必要的,您可以执行#{456}.

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

这篇关于Ruby:带字符串插值的eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆