By default heredocs in Ruby behave like double-quoted strings when it comes to interpolation and escape characters:

land = 'Mordor'

verse = <<-TEXT
One Ring to rule them all,
One Ring to find them,
One Ring to bring them all,
and in the darkness bind them,
In the Land of #{land} where the Shadows lie.
TEXT

# => "One Ring to rule them all,\n" +
# "One Ring to find them,\n" +
# "One Ring to bring them all,\n" +
# "and in the darkness bind them,\n" +
# "In the Land of Mordor where the Shadows lie.\n"

There’s a way to suppress this behavior and make heredocs behave like single-quoted strings, but it’s a little bit… weird1:

land = 'Mordor'

verse = <<-'TEXT'
One Ring to rule them all,
One Ring to find them,
One Ring to bring them all,
and in the darkness bind them,
In the Land of #{land} where the Shadows lie.
TEXT

# => "One Ring to rule them all,\n" +
# "One Ring to find them,\n" +
# "One Ring to bring them all,\n" +
# "and in the darkness bind them,\n" +
# "In the Land of \#{land} where the Shadows lie.\n"

This works for both normal and squiggly heredocs (<<~). Notice that you have to put only the opening delimiter within single quotes.

That’s all I have for you today! Keep hacking and keep Ruby weird!

Articles in the Series

  1. Unless you’re into Perl.