我不明白为什么string.size返回它的作用

Lux*_*ode 7 ruby heredoc

long_string = <<EOS
It was the best of times,
It was the worst of times.
EOS
Run Code Online (Sandbox Code Playgroud)

返回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
Run Code Online (Sandbox Code Playgroud)

是这种情况,因为%{case将每个/n字符统计为一个字符,并且在第一行之前认为是一个字符,一个在结尾处,然后在第二行结尾处,而在这种EOS情况下只有一个在第一行之前线和一线后一线?换句话说,为什么前者54和后者53?

Zab*_*bba 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
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)

这个怎么运作:

在这种情况下<<EOS,它后面的行是字符串的一部分.<<在行的相同行<<和行的末尾之后的所有文本将是"标记"的一部分,该标记确定字符串何时结束(在这种情况下EOS,行本身就是匹配的<<EOS).

在这种情况下%{...},它只是一个不同的分隔符代替"...".所以当你在a之后的新行上开始字符串时%{,该换行符就是字符串的一部分.

试试这个例子,您将看到如何%{...}工作"...":

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
Run Code Online (Sandbox Code Playgroud)