Weird Ruby: Single-quoted Heredocs
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
- Weird Ruby: Pure Object-Oriented Negation
- Weird Ruby: Positive and Negative Strings
- Weird Ruby: Double Negation
- Weird Ruby: Single-quoted Heredocs
- Weird Ruby: Block Comments
- Weird Ruby: Zeroing in on a Couple of Numeric Predicates
- Weird Ruby: Invoking Lambdas
- Weird Ruby: For Loops
- Weird Ruby: Array Multiplication
- Weird Ruby: Heredoc Delimiters
- Weird Ruby: Mixing Code and Data
- Weird Ruby: A Weird Way to Filter Out Elements
- Weird Ruby: Nil Conversions
- Weird Ruby: Fun with String#split
- Weird Ruby: Incrementing Strings
- Weird Ruby: The Double Aliased Enumerable Method
-
Unless you’re into Perl. ↩