Search code examples
rubystringquotes

Do flexible quotes add an extra character to a string?


I was learning ruby through ruby koans when I faced these two functions:

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

The problem is I cannot understand where this extra character is coming from when using flexible quotes. Ruby koans says that both answers are correct.


Solution

  • I'd say it's a newline character after %{.

    >> test = %{
    ">> foo
    ">> }
    => "\nfoo\n"
    >> test.size
    => 5
    >> test = %{foo
    ">> }
    => "foo\n"
    >> test.size
    => 4
    >> test = <<EOS
    ">> foo
    ">> EOS
    => "foo\n"
    >> test.size
    => 4