2015-10-26 50 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