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

时间:2011-06-14 00:08:14

标签: ruby heredoc

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?

1 个答案:

答案 0 :(得分: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

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