long_string = <<EOS It was the best of times,It was the worst of times. EOS
返回53.为什么?空白计数?即便如此.我们怎么得到53?
这个怎么样?
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
是这种情况,因为%{case将每个/ n计为一个字符,并且在第一行之前认为是一个,最后一个,然后在第二行的末尾,而在EOS情况下只有一个在第1行之前和第1行之后?换句话说,为什么前者54和后者53?
解决方法
对于:
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