从字符串执行内联ruby

Las*_*and 0 ruby

我试图从字符串中执行内联ruby.该字符串作为文本存储在数据库中,而不是使用ruby创建的.

string = 'The year now is #{Time.now.year}'
puts string
Run Code Online (Sandbox Code Playgroud)

那回来了

=> The year now is #{Time.now.year}
Run Code Online (Sandbox Code Playgroud)

我想要它回来

=> The year now is 2015
Run Code Online (Sandbox Code Playgroud)

ruby中有没有像这样执行内联ruby的方法?

non*_*ndo 6

是的,你的工作不起作用的唯一原因是单引号导致字符串文字(意味着没有转义或嵌入').

string = "The year now is #{Time.now.year}"
puts string
Run Code Online (Sandbox Code Playgroud)

会工作(注意双引号).

编辑1:

另一个解决方案(eval除外)是使用字符串插值.

string = 'Time is: %s' 
puts string % [Time.now.year]
Run Code Online (Sandbox Code Playgroud)

所以,您可以用以下代码替换%s:

string = 'The year now is %s' 
 => "The year now is %s" 
2.2.1 :012 > string % [Time.now.year]
 => "The year now is 2015" 
Run Code Online (Sandbox Code Playgroud)

更多这里.