I don't understand why string.size returns what it does
long_string = <<EOS
It was the best of times,
It was the worst of times.
EOS
that returns 53. Why? The whitespace counts? Even still. how do we get 53?
How about this?
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
Is this the case because the %{ case counts each /n
as one character and theres considered to be one before the first line, one at the end, and then at the end of the 2nd line, whereas in the EOS
case theres just one before the 1st line and one after the 1st line? In other words, why is the former 54 and the latter 53?
For:
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
And
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"
How it works:
In the case of <<EOS
, the lines that follow it are part of the string. All the text after <<
on the same line as <<
and to the end of the line would be part of the "marker" that determines when the string ends (in this case an EOS
on a line by itself is matching the <<EOS
).
In case of %{...}
, it is just a different delimiter used in place of "..."
. So when you have the string starting on a new line after a %{
, that newline is part of the string.
Try this example and you will see how %{...}
is working same as "..."
:
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
精彩评论