2011-06-14 97 views
7
long_string = <<EOS 
It was the best of times, 
It was the worst of times. 
EOS 

返回53.爲什麼?空白的數量?即使如此。我們如何得到53?我不明白爲什麼string.size返回它所做的

這個怎麼樣?

 def test_flexible_quotes_can_handle_multiple_lines 
    long_string = %{ 
It was the best of times, 
It was the worst of times. 
} 
    assert_equal 54, long_string.size 
    end 

    def test_here_documents_can_also_handle_multiple_lines 
    long_string = <<EOS 
It was the best of times, 
It was the worst of times. 
EOS 
    assert_equal 53, long_string.size 
    end 

是這種情況,因爲%{情況下,可計算每個/n爲一個字符,被認爲是一個第一行之前,一個在端孤單,然後在第2行的末尾,而在EOS這種情況在第一行之前只有一個,第一行之後有一個?換句話說,爲什麼前者54和後者53?

+0

哦,請不狄更斯行情... – alternative 2011-06-14 00:14:04

回答

14

爲:

long_string = <<EOS 
It was the best of times, 
It was the worst of times. 
EOS 

String is: 
"It was the best of times,\nIt was the worst of times.\n" 

It was the best of times, => 25 
<newline> => 1 
It was the worst of times. => 26 
<newline> => 1 
Total = 25 + 1 + 26 + 1 = 53 

而且

long_string = %{ 
It was the best of times, 
It was the worst of times. 
} 

String is: 
"\nIt was the best of times,\nIt was the worst of times.\n" 
#Note leading "\n" 

工作原理:

<<EOS的情況下,它後面的線是字符串的一部分。 <<<<相同,並且在行末尾的所有文本將成爲確定字符串何時結束的「標記」的一部分(在這種情況下,行上的EOS本身與<<EOS匹配)。

%{...}的情況下,它只是一個不同的分隔符代替"..."。所以當你在%{之後的新行開始時,該換行符就是字符串的一部分。

試試這個例子,你會看到%{...}如何爲"..."工作一樣:

a = " 
It was the best of times, 
It was the worst of times. 
" 
a.length # => 54 

b = "It was the best of times, 
It was the worst of times. 
" 
b.length # => 53 
+0

這就是我算過。 – kinakuta 2011-06-14 00:12:51

相關問題