我不明白为什么 string.size 返回它的作用
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 的情况下,第一行之前只有一个,第一行之后只有一个?也就是说,为什么前者是54,后者是53呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于:
以及
如何工作:
在
< 的情况下,其后面的行是字符串的一部分。与
<<
同一行的<<
之后以及到该行末尾的所有文本都将成为“标记”的一部分,用于确定何时字符串结束(在这种情况下,一行中的EOS
本身与< 匹配)。
对于
%{...}
,它只是用来代替"..."
的不同分隔符。因此,当字符串在%{
之后开始新行时,该换行符就是字符串的一部分。尝试这个示例,您将看到
%{...}
的工作方式与"..."
相同:For:
And
How it works:
In the case of
<<EOS
, the lines that follow it are part of the string. All the text after<<
on the same line as<<
and to the end of the line would be part of the "marker" that determines when the string ends (in this case anEOS
on a line by itself is matching the<<EOS
).In case of
%{...}
, it is just a different delimiter used in place of"..."
. So when you have the string starting on a new line after a%{
, that newline is part of the string.Try this example and you will see how
%{...}
is working same as"..."
: