Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding ruby quine

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?

like image 876
knub Avatar asked Jun 03 '12 19:06

knub


2 Answers

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 with something.

So structurally, the program is just doing this:

puts str*2,2

... 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:

puts <<2*2,2
puts <<2*2,2
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 is puts, each of those things gets a newline appended automatically.)

like image 182
Mark Reed Avatar answered Sep 23 '22 14:09

Mark Reed


In ruby, you can define strings with

str = <<DELIMITER
  long string
  on several
  lines
DELIMITER

I suppose that from here, you can guess the rest :)

like image 2
ksol Avatar answered Sep 23 '22 14:09

ksol