185 views
What's the return value of the following Ruby code?
a = <<'"}{|_(_&^+$^)$_$345_$#%$^%^+' visit ukod.me "}{|_(_&^+$^)$_$345_$#%$^%^+ a # => ???
The correct answer is
"visit ukod.me\n"
"visit ukod.me"
SyntaxError
false
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
In Ruby, heredocs allow you to create multi-line strings in a flexible way. Typically, we use simple delimiters like <<EOF
to open and EOF
to close the string.
However, Ruby is remarkably flexible with what you can use as the delimiter name, especially when using single-quoted heredoc delimiters (<<'DELIM'
).
Let's explore an example that pushes this concept to its limits:
<<'"}|{_(_&^+$^)$_$345_$#%$^%^+' visit ukod.me "}|{_(_&^+$^)$_$345_$#%$^%^+ # => "visit ukod.me\n"
Heredoc syntax allows you to create a multi-line string using <<'DELIM'
.
The delimiter DELIM
can be almost anything as long as it starts the heredoc and ends it consistently.
In this case, the delimiter used is "}|{_(_&^+$^)$_$345_$#%$^%^+
, which is a very unusual combination of symbols.
Ruby doesn’t care—as long as the start and end match exactly, it's valid.
The content between the heredoc delimiters is visit ukod.me
. This is what gets assigned to the heredoc, and it ends with a newline (\n
).
Ruby allows almost any sequence of characters as a heredoc delimiter when it is single-quoted.
This includes spaces, symbols, or even unusual combinations of punctuation, as long as the opening and closing delimiters match exactly.
This flexibility is part of what makes Ruby fun and expressive, but it can also lead to confusing code if not used carefully.
While this is an interesting aspect of Ruby, it's best to avoid using such convoluted delimiters in practice.
Code readability is crucial, and most editors might struggle to handle such strange delimiter names properly.
Instead, sticking to simple, meaningful delimiter names like EOF
or HTML
will make your code much more approachable for others (and for yourself, when you come back to it later).
In summary, Ruby's heredoc delimiter rules are incredibly flexible, allowing you to use even the most bizarre sequences as delimiters.
While this is an interesting feature, it's usually best left in the realm of "weird Ruby tricks" rather than everyday code.
What's new on RubyCademy?
Quick heads-up:
💚
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©