在Ruby中,如何在定义这些变量之前定义带插值变量的字符串?
一旦这些变量分配了值,我需要做什么才能进行插值?
tips = 'Hi,#{name},your order total price is #{price*count}'
name = 'roy'
price = 13.5
count = 10
tips.xxx = 'Hi,roy,your order total price is 135'
答案 0 :(得分:1)
为了评估#{...}
之间的所有Ruby代码,你必须使用双引号,否则它只是打印为commong String。我想你想要返回像'Hi,roy,your order total price is 135'
这样的东西,所以,你需要先创建名称,价格和计数变量,因为如果你不这样做,那么你会得到一个undefined local variable or method 'variable' for main:Object
错误,所以你可以试试:
name = 'roy'
price = 13.5
count = 10
tips = "Hi,#{name},your order total price is #{price*count}"
puts tips
# Hi,roy,your order total price is 135.0
答案 1 :(得分:1)
对于您的情况,您可以使用late interpolation
:
tips = 'Hi, %{name},your order total price is %{price}'
name = 'roy'
price = 13.5
count = 10
tips % {name: name, price: price * count}
# => "Hi,roy,your order total price is 135"
文档链接:https://ruby-doc.org/core-2.4.1/String.html#method-i-25