The First Quines in Ruby


Originally posted to the ruby-talk list on July 19, 2000


Maybe you are familiar with the practice of writing programs that reproduce themselves. (I always liked Plauger's comment -- I think it was Plauger -- who said, "This is often done in FORTRAN, for the same reason that three-legged races are popular.")

The word quine comes from the name of the mathematician Willard van Orman Quine, by way of Douglas Hofstadter's book Goedel, Escher, Bach.

My understanding is that any Turing-complete language is capable of reproducing itself -- i.e., all but the most trivial and useless languages. (I'm only repeating what I've heard -- I'm not that much of a theorist.)

By the way, it is considered cheating to access a file (for example, cat $(whence $0) in Kornshell) or to use a built-in listing feature (like 10 LIST 10 in BASIC).

Anyway, I was curious as to whether it had been done in Ruby yet. A search of the mailing list archive didn't turn up anything. So unless someone speaks up, I claim the first one in Ruby.

Here are three different ones. The first is a ripoff of a famous quine in C, working only on ASCII machines.

  s="s=%c%s%c; printf s,34,s,34,10%c"; printf s,34,s,34,10

The next one uses a here-document type of string.

  a=<<'EOF'
  print "a=<<'EOF'"
  print a
  print "EOF\n"
  print a
  EOF
  print "a=<<'EOF'"
  print a
  print "EOF\n"
  print a

The third one is a little more tricky and a little more fragile.

  $a=%w( def xx
  $a.each do |x| if x =~ /xx/
  print x+"\n" else print x, " " end end end; print "$a=%w( "; xx
  print ")\n"; xx
  )
  def xx
  $a.each do |x| if x =~ /xx/
  print x+"\n" else print x, " " end end end; print "$a=%w( "; xx
  print ")\n"; xx

That's all, folks. Have a great day!


Hal Fulton

Back to my Ruby page