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

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情况下只有一个在第1行之前和第1行之后?换句话说,为什么前者54和后者53?

解决方法

对于:
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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...