← Back to Ruby Operators

Triple Quote

Have you ever seen a block of text wrapped on both ends by """ (triple quotes)? This purported multi-line syntax shows up in Ruby codebases from time to time.

query = """
  select date_part('day', created_at),
    array_agg(user.email)
  from users
  where active = true
    and created_at between '2024-11-13' and '2024-11-15'
  group by date_part('day', created_at)
  order by date_part('day', created_at);
"""

This alleged multi-line syntax is an illusion, a trick of the light. What we're really seeing here is a shorthand that Ruby provides for concatenating strings.

Check out this series of IRB statements to get an intuition for what is actually going on.

> ""
=> ""
> "" ""
=> ""
> "one" "two"
=> "onetwo"
> "" "a" ""
=> "a"
> """a"""
=> "a"
" """
" a
> """
=> "
a
"

Any two string literals next to one another will be concatenated. What we are seeing with the triple-quote "syntax" is really just putting an extra empty string on either side of a string that contains, say, our SQL.

Technically we can create multi-line strings with quotes on their own.

" "
" a
"   b
"     c
> "
=> "
a
  b
    c
"

The real takeaway is that if you want a multi-line string, you should reach for one of the heredoc syntaxes.

Under the hood

It seems to me that the parser is probably where these consecutive strings are getting smooshed together. I'm basing that on this disassmebled output which only shows a single putstring instruction.

$ ruby --dump=insns -e '"" "a" ""'
== disasm: #<ISeq:<main>@-e:1 (1,0)-(1,9)> (catch: false)
0000 putstring                              "a"                       (   1)[Li]
0002 leave

References