2011-06-14 50 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

相关问题