8
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?

4

1 回答 1

15

为了:

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 之后的新行开始时%{,该换行符是字符串的一部分。

试试这个例子,你会看到它%{...}是如何工作的"..."

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
于 2011-06-14T00:11:04.510 回答