ruby - 这是什么意思?

标签 ruby

例如《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

最佳答案

在 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"

关于ruby - 这是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18089993/

相关文章:

ruby-on-rails - 如何编写和继承 ActionController::TestCase 的抽象子类

ruby - 此代码是否在 Ruby 中创建循环内存引用?

ruby - "public"和 "private"是类,而 "protected"不是?

ruby-on-rails - 如何使用 jquery-Tokeninput 和 Acts-as-taggable-on

ruby - Ruby 数组中的基本方向

ruby-on-rails - gem install rmagick -v 2.13.1 错误 Failed to build gem native extension on Mac OS 10.9.1

ruby-on-rails - 如何使用 ruby​​ 读取表单数据

ruby-on-rails - 如何在初始构建失败后在 CodeClimate 上开始另一个构建?

ruby - 使用 Mechanize 显示数据页面的屏幕抓取网页

ruby-on-rails - 如何计算多对多模型的特征向量?