问题描述
||
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
,其后的行是字符串的一部分。 <<
之后与<<
在同一行上并到该行末尾的所有文本都是确定字符串何时结束的\“ marker \”的一部分(在这种情况下,一行上的EOS
本身与<<EOS
匹配) 。
在“ 11”的情况下,它只是代替“ 12”的分隔符。因此,当字符串在%{
之后从新行开始时,该换行符就是字符串的一部分。
尝试以下示例,您将看到%{...}
与\"...\"
的工作方式相同:
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