A Ruby Quine
by Stephen Pike

I wrote a quine! A quine is a program that generates exactly its own source code.

c = ['puts "c = [#{c[2]}#{c[0]}#{c[2]},
#{c[2]}#{c[1]}#{c[2]},
#{c[3]}#{c[2]}#{c[3]},
#{c[2]}#{c[3]}#{c[2]}]"',
'c[0..1].each { |y| puts y }',
"'",
'"']
puts "c = [#{c[2]}#{c[0]}#{c[2]},
#{c[2]}#{c[1]}#{c[2]},
#{c[3]}#{c[2]}#{c[3]},
#{c[2]}#{c[3]}#{c[2]}]"
c[0..1].each { |y| puts y }

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:

c = ['puts "c = [#{c[1]}#{c[0]}#{c[1]},
#{c[2]}#{c[1]}#{c[2]},
#{c[1]}#{c[2]}#{c[1]}]"',
"'",
'"']
puts "c = [#{c[1]}#{c[0]}#{c[1]},
#{c[2]}#{c[1]}#{c[2]},
#{c[1]}#{c[2]}#{c[1]}]"

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

c = ['puts "c = [#{c[1]}#{c[0]}#{c[1]},
#{c[2]}#{c[1]}#{c[2]},
#{c[1]}#{c[2]}#{c[1]}]"',
"'",
'"']

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:

c = ['puts "c = [#{39.chr}#{c[0]}#{39.chr},#{39.chr}#{c[1]}#{39.chr}]"',
'c[0..1].each { |y| puts y }']
puts "c = [#{39.chr}#{c[0]}#{39.chr},#{39.chr}#{c[1]}#{39.chr}]"
c[0..1].each { |y| puts y }

And finally, here’s another version that uses eval and %q to skip out on some of the duplication:

c = [%q!puts "c = [#{37.chr}q#{33.chr}#{c[0]}#{33.chr},
'#{c[1]}','#{c[2]}']"!,
'eval c[0]','c[1..2].each { |y| puts y }']
eval c[0]
c[1..2].each { |y| puts y }

There’s also a much nicer clojure version.