![](/img/trans.png)
[英]Michael Hartl Rails tutorial: assert_not does exact opposite of what it should and I don't understand why
[英]I don't understand why string.size returns what it does
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
是這種情況嗎,因為 %{ 案例將每個/n
視為一個字符,並且在第一行之前被認為是一個,在末尾一個,然后在第二行末尾,而在EOS
案例中只有一個在第一行之前和第一行之后? 也就是說,為什么前者是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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.