2015-10-26 36 views
9

我想让自己熟悉ruby的语法和编码风格(我是一个新手)。我遇到了一个使用<<-的代码,这在Ruby中意味着什么?代码是双倍小于减“<< - ”符号是否意味着任何红宝石?

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

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

+1

这是红宝石定界符。你可以在这里阅读:http://blog.jayfields.com/2006/12/ruby-multiline-strings-here-doc-or.html –

回答

6

有各种方法在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

此外,即使是-(破折号)是不需要的。但是,允许您缩进“这里的文档结束”分隔符。看下面的例子来理解句子。

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/

+1

在OP的情况下,短划线_is_需要(允许缩进结束标记) –

+2

“他们都支持插值” - 不正确。单引号字符串不允许插值。 –

+0

好的,确保你完成后在这里勾选其中一个答案。 :) – illusionist

4

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

More info