Stupid Ruby Quoting Tricks

February 26, 2008 Pivotal Labs

Let’s start with something easy.

Here’s the mirepoix

bar = "chicken"

You know single quotes and double quotes, right? These are our salt and pepper.

'frickin #{bar}' # => "frickin #{bar}"
"frickin #{bar}" # => "frickin chicken"

Have you seen %%q and %%Q?

%%q(frickin #{bar}) # => "frickin #{bar}"
%%Q(frickin #{bar}) # => "frickin chicken"
%%q{frickin #{bar}} # => "frickin #{bar}"
%%Q{frickin #{bar}} # => "frickin chicken"

You’ve also seen “”” (triple-quotes) right?

"""frickin #{bar}""" # => "fricken chicken"
"""frickin '#{bar}'""" # => "fricken 'chicken'"
"""frickin "#{bar}"""" # => "fricken "

UPDATE: As John points out in the comments, in addition to triple quotes there are also quintuple quotes, septuple quotes, and so forth. In fact, you can invent your own quoting operator for any odd number of quotes. (Just kidding.)

The truth is, singly and doubly-quoted object concatenate simply by juxtaposition!

"frickin " "chicken" # => "fricken chicken"
'frickin ' 'chicken' # => "fricken chicken"
"frickin " bar # => kabooom!
%%q{frickin } %%q{chicken} # => kablooey!
"""" #=> ""
"""frickin chicken" # => "frickin chicken"

Hokay. So that is all child’s play. These are the quoting operators for the big boys.

This is why Ruby’s Grammar is not Context-Free:

def foo(x)
  x.reverse
end

foo(<<-EOS)
  Your mom
EOS
# => "mom ruoY"

foo(<<-EOS).reverse
  amanaplanacanalpanama
EOS
# => "amanaplanacanalpanama"

Even better:

puts(DATA.read.reverse)

__END__
Your mom
# => "mom ruoY"

You actually have to copy the above code into a ruby file and run it — it wont work in IRB.

About the Author

Biography

More Content by Pivotal Labs
Previous
Can less leave the screen alone when it quits?
Can less leave the screen alone when it quits?

From the less faq: blah blah blah ti/te blah blah blah -X blah blah. Also, -R makes it show ANSI c...

Next
dri on openbsd/amd64
dri on openbsd/amd64

I've been helping out oga@ with the porting of dri onto OpenBSD, specifically in the !i386 sense. I'm also...

Enter curious. Exit smarter.

Learn More