问题 是否小于负“


我试图让自己熟悉ruby语法和编码样式(我是新手)。我遇到了一个使用的代码 <<-,这在Ruby中意味着什么?代码是

  def expectation_message(expectation)
    <<-FE
      #{expectation.message}
      #{expectation.stack}
    FE
  end

这只是整个代码的一部分。任何帮助,将不胜感激。


3105
2017-10-26 11:06


起源

这是ruby heredoc语法。你可以在这里读到它: blog.jayfields.com/2006/12/... - Sergei Stralenia


答案:


有多种方法可以在Ruby中定义多行字符串。这是其中之一。

> name = 'John'
> city = 'Ny'
> multiline_string = <<-EOS
> This is the first line
> My name is #{name}.
> My city is #{city} city.
> EOS
 => "This is the first line\nMy name is John.\nMy city is Ny city.\n" 
>

EOS 在上面的示例中只是一个约定,您可以使用您喜欢的任何字符串及其不区分大小写。通常是 EOS 手段 End Of String

而且,即使是 - (破折号)不需要。但是,允许您缩进“此处doc结束”分隔符。请参阅以下示例以了解句子。

2.2.1 :014 > <<EOF
2.2.1 :015"> My first line without dash
2.2.1 :016">         EOF
2.2.1 :017"> EOF
 => "My first line without dash\n        EOF\n" 


2.2.1 :018 > <<-EOF
2.2.1 :019"> My first line with dash. This even supports spaces before the ending delimiter.
2.2.1 :020">    EOF
 => "My first line with dash. This even supports spaces before the ending delimiter.\n" 
2.2.1 :021 > 

有关详情,请参阅 https://cbabhusal.wordpress.com/2015/10/06/ruby-multiline-string-definition/


10
2017-10-26 11:16



在OP的情况下破折号 是 需要(允许缩进结束标记) - Sergio Tulentsev
“他们都支持插值” - 不是真的。单引号字符串不允许插值。 - Sergio Tulentsev
好的,确保在完成后勾选其中一个答案。 :) - illusionist
第二个例子,用 <<- 语法为我抛出一个错误。我需要将值赋给变量,否则我会得到一个未初始化的常量错误。 - kapad


<<FE (您可以用另一个词替换FE)用于创建多行字符串。 <<-FE 用于在删除结束标记之前创建具有空白的多行字符串。

更多信息


4
2017-10-26 11:11