在一個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
是的,現在很徹底。 –