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を 1 文字としてカウントし、最初の行の前に 1 つ、最後に 1 つ、次に 2 行目の最後にあると見なされるため、これはEOS当てはまります。行と1行目の後の1つ?つまり、なぜ前者が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 = "
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 に答える