我对Ruby有点新意,我想在String中替换局部变量。如果我有:
user = "foo"
pass = "bar"
puts "if you #{user}, you should #{bar}"
#prints: if you foo, you should bar
但在我的情况下,String是文件中的一行文本,因此不会在分析时声明。是否有任何内置功能可以跟上这个机制?
答案 0 :(得分:4)
string = "if you %{user}, you should %{pass}"
string % {user: "foo", pass: "bar"}
# => "if you foo, you should bar"