在一个Ruby双引号字符串 - 包括字符串文字等s = "…"
和s = %Q{ ... }
和s = <<ENDCODE
-语法#{ … }
用于“字符串插值”,将动态内容插入到字符串中。例如:
i = 42
s = "I have #{ i } cats!"
#=> "I have 42 cats!"
它等同于(而且更方便比有效)使用字符串连接用显式调用to_s
沿:
i = 42
s= "I have " + i.to_s + " cats!"
#=> "I have 42 cats!"
您可以将任意代码的区域内,包括多行上的多个表达式。评估代码的最终结果已呼吁其to_s
,以确保它是一个字符串值:
"I've seen #{
i = 10
5.times{ i+=1 }
i*2
} weasels in my life"
#=> "I've seen 30 weasels in my life"
[4,3,2,1,"no"].each do |legs|
puts "The frog has #{legs} leg#{:s if legs!=1}"
end
#=> The frog has 4 legs
#=> The frog has 3 legs
#=> The frog has 2 legs
#=> The frog has 1 leg
#=> The frog has no legs
注意,这有单引号字符串里面没有任何影响:
s = "The answer is #{6*7}" #=> "The answer is 42"
s = 'The answer is #{6*7}' #=> "The answer is #{6*7}"
s = %Q[The answer is #{ 6*7 }] #=> "The answer is 42"
s = %q[The answer is #{ 6*7 }] #=> "The answer is #{6*7}"
s = <<ENDSTRING
The answer is #{6*7}
ENDSTRING
#=> "The answer is 42\n"
s = <<'ENDSTRING'
The answer is #{6*7}
ENDSTRING
#=> "The answer is #{6*7}\n"
为了方便起见,如果您只想插入实例变量(@foo
),全局变量的值,则可以选择用于字符串插值的{}
字符变量($foo
),或类变量(@@foo
):
@cats = 17
s1 = "There are #{@cats} cats" #=> "There are 17 cats"
s2 = "There are #@cats cats" #=> "There are 17 cats"
您可能希望在括号内添加该间距不相关。 ''我拥有#{i}猫''也是有效的。 –
@NielsB。您是否同意编辑清楚地说明了这一点,因为您可以有多行,并且有些例子显示没有空格? – Phrogz
是的,现在很彻底。 –