Ruby {…}是什么意思?
例如,在《为什么》的《辛酸指南》中的以下代码中:Ruby {…}是什么意思?,ruby,Ruby,例如,在《为什么》的《辛酸指南》中的以下代码中: def wipe_mutterings_from( sentence ) unless sentence.respond_to? :include? raise ArgumentError, "cannot wipe mutterings from a #{ sentence.class }" end while sentence.include? '(' open = sent
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
“#{}”
在Ruby字符串插值中的意思。有关太多的答案,请参阅。#{}
用于Ruby插值。在这个例子中
这将在消息中引发ArgumentError
无法从文件中删除喃喃自语
在Ruby双引号字符串中,这是一个有用的读取-,其中包括字符串文本,如
s=“…”
和s=%Q{…}
和s=字符串插值意味着变量/表达式的内容被放入该位置的嵌入字符串中。您可能需要添加括号内的间距不相关<代码>“我有{I}只猫”
也有效。@NielsB。考虑到你可以有多行,而且有一些例子显示没有空格,你是否同意编辑明确了这一点?是的,现在已经非常彻底了。
i = 42
s = "I have #{ i } cats!"
#=> "I have 42 cats!"
i = 42
s= "I have " + i.to_s + " cats!"
#=> "I have 42 cats!"
"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"
@cats = 17
s1 = "There are #{@cats} cats" #=> "There are 17 cats"
s2 = "There are #@cats cats" #=> "There are 17 cats"