I can remember, once, long ago, being entranced with the idea of writing programs whose output was identical to its own code. This is, of course, entirely impractical and not really good for anything.
Ruby has a built-in variable, $0, which refers to the name of ruby program currently being executed, and which therefore makes the writing of self-describing programs trivial. So, you can write a ruby program which outputs itself like so:
1 2 | #!/usr/bin/ruby IO::readlines($0).each{|n|puts n} |
Pretty nifty. Can it get any shorter? If you’re willing to use bash commands, yes it can:
1 2 | #!/usr/bin/ruby system("cat #{$0}") |
If you want to dispense with the shebang and run it with ruby stupid.rb (or whatever you’d like to title your work of art) then you can shave another 15 characters off of it. The shortest way I could see to get it would be
1 | puts `cat #{$0}` |
which assumes you have to run it with ruby ... rather than just with it’s own name. That’s all rather pointless, of course.
Of course, the $0 variable also means that you can do exciting things like rewrite the file which is currently executing while you’re executing it:
1 2 | #!/usr/bin/ruby File::open($0,mode="w").write('puts "Hello #{`whoami`}"') |
Have fun with that. Oh, and, um… only try this at home.
Try this ;-)
eval `cat #{$0}`
Good alternative; although, 'puts' and 'eval' are the same length. I think those are as short as it gets for something like that.
Technically, using $0 is sort of “cheating” — if I remember right, part of the challenge of writing a program whose output is its own source code was doing so without resorting to simply reading and outputting the source file… Using something like $0 is much easier, of course. :-)
Something like
_="_=%p;puts _%%_";puts _%_(which I didn't write; found that at http://thisbindle.com/personal/ruby/)