首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >{…}什么意思?

{…}什么意思?
EN

Stack Overflow用户
提问于 2013-08-06 20:37:17
回答 3查看 977关注 0票数 2

如“为什么是痛苦指南”中的以下代码:

代码语言:javascript
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-08-06 20:42:05

在Ruby双引号字符串(包括s = "…"s = %Q{ ... }等字符串文字)和s = <<ENDCODE-the语法中,#{ … }用于“字符串内插”,将动态内容插入到字符串中。例如:

代码语言:javascript
复制
i = 42
s = "I have #{ i } cats!"
#=> "I have 42 cats!"

它与使用字符串连接以及显式调用相比(但比使用更方便的to_s更有效)等效。

代码语言:javascript
复制
i = 42
s= "I have " + i.to_s + " cats!"
#=> "I have 42 cats!"

您可以在区域内放置任意代码,包括多行上的多个表达式。评估代码的最终结果是to_s调用它以确保它是一个字符串值:

代码语言:javascript
复制
"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

请注意,这在单引号字符串中没有任何影响:

代码语言:javascript
复制
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)的值,用于字符串内插的@foo字符是可选的:

代码语言:javascript
复制
@cats = 17
s1 = "There are #{@cats} cats" #=> "There are 17 cats"
s2 = "There are #@cats cats"   #=> "There are 17 cats"
票数 6
EN

Stack Overflow用户

发布于 2013-08-06 20:38:22

"#{}"的意思是在Ruby interpolation.See Here中有太多答案。

票数 4
EN

Stack Overflow用户

发布于 2013-08-06 20:40:54

#{}用于红宝石插值。在这个例子中,

这将引发带有消息的ArgumentError,

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18089993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档