这是什么意思?

时间:2013-08-06 20:37:18

标签: 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 = sentence.index( '(' )
         close = sentence.index( ')', open )
         sentence[open..close] = '' if close
     end
end

3 个答案:

答案 0 :(得分: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"

答案 1 :(得分:4)

"#{}"表示Ruby字符串插值。请Here查看太多答案。

答案 2 :(得分:1)

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

这将引发带有消息

的ArgumentError

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

这是一个有用的阅读 - String concatenation vs. interpolation in Ruby