【问题标题】:I don't understand why string.size returns what it does我不明白为什么 string.size 返回它的作用
【发布时间】:2011-09-14 07:58:06
【问题描述】:
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 视为一个字符,并且在第一行之前被认为是一个字符,在末尾一个,然后在第二行末尾,而在 @ 987654324@ 情况下只有一个在第一行之前和一个在第一行之后?也就是说,为什么前者是54,后者是53?

【问题讨论】:

  • 哦,请不要引用查尔斯狄更斯的名言......

标签: ruby heredoc


【解决方案1】:

为:

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"

工作原理:

对于&lt;&lt;EOS,它后面的行是字符串的一部分。 &lt;&lt; 之后的所有文本与 &lt;&lt; 位于同一行并到行尾将是确定字符串何时结束的“标记”的一部分(在这种情况下,一行上的 EOS 本身是匹配&lt;&lt;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

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 2023-02-05
    • 2015-09-12
    • 2019-06-09
    • 2021-10-20
    • 2014-04-20
    相关资源
    最近更新 更多