2

例如Why's Poignant Guide中的以下代码:

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
4

3 回答 3

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"
于 2013-08-06T20:42:05.107 回答
4

"#{}"表示在 Ruby 字符串插值Here中。请参阅太多答案。

于 2013-08-06T20:38:22.477 回答
1

#{}用于 Ruby 插值。在这个例子中,

这将引发带有消息的 ArgumentError,

cannot wipe mutterings from a <whatever sentence.class evaluates to>

这是一个有用的阅读 -字符串连接与 Ruby 中的插值

于 2013-08-06T20:40:54.493 回答