I wrote a quine! A quine is a program that generates exactly its own source code.
This starts by building an array which contains as its first element a
string which is a valid ruby command that would define that array:
c[0]
is a statement that prints the string "c =
[ ... definition of c ... ]"
. It works via delayed string
interpolation; wrapping with single quotes defers calls to
#{c[0}}
, #{c[1]}
, etc.,
With just that first piece, our quine would look like:
(the two extra entries in c
are because I had trouble getting string interpolation to work with both ‘ and “ characters, so I needed a way to refer to those tokens).
When you run this program, you get:
So we’ve got a program which when run prints the code which generates
the array c
. But how do we also print the code which prints the code
which prints c
(the puts statement itself)? It’s
turtles all the way down!
Fortunately we have one new tool available that lets us break this
loop. We can add another command to c
that calls puts
on both the
first element of c
and itself: 'c[0..1].each { |y| puts y
}'
. It works!
There are much more elegant ruby quines
out on the internet. They
get around my ugly string interpolation problem by calling chr
on
numbers to convert ascii codes to characters directly. With that
trick, and the knowledge that 39.chr == "'"
, we can remove the last
two entries in c
and come to the much shorter:
And finally, here’s another version that uses eval and %q
to skip
out on some of the duplication:
There’s also a much nicer clojure version.