2013-08-06 287 views
2

如從爲什麼的悽美指南下面的代碼:#{...}是什麼意思?

def wipe_mutterings_from(sentence) 
    unless sentence.respond_to? :include? 
     raise ArgumentError, "cannot wipe mutterings from a #{ sentence.class }" 
    end 
    while sentence.include? '(' 
     open = sentence.index('(') 
     close = sentence.index(')', open) 
     sentence[open..close] = '' if close 
    end 
end 

回答

6

在一個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" 
+0

您可能希望在括號內添加該間距不相關。 ''我擁有#{i}貓''也是有效的。 –

+0

@NielsB。您是否同意編輯清楚地說明了這一點,因爲您可以有多行,並且有些例子顯示沒有空格? – Phrogz

+0

是的,現在很徹底。 –

4

"#{}"意味着在Ruby中的字符串interpolation.See Here太多的答案。

+2

和字符串插值意味着變量/表達的內容被放入在該位置處的嵌入的字符串。 – mnagel