I have found this code block on Wikipedia as an example of a quine (program that prints itself) in Ruby.
puts <<2*2,2
puts <<2*2,2
2
However, I do not get how it works. Especially, what I do not get is that when I remove the last line, I get this error:
syntax error, unexpected $end, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
What happens in those lines?
The
<<something
syntax begins a here-document, borrowed from UNIX shells via Perl - it's basically a multiline string literal that starts on the line after the<<
and ends when a line starts withsomething
.So structurally, the program is just doing this:
... that is, print two copies of
str
followed by the number 2.But instead of the variable
str
, it's including a literal string via a here-document whose ending sentinel is also the digit 2:So it prints out two copies of the string
puts <<2*2,2
, followed by a 2. (And since the method used to print them out isputs
, each of those things gets a newline appended automatically.)