Demystifying @tenderlove's homeopathic code optimizations
At the Keep Ruby Weird conference, Aaron Patterson, aka @tenderlove, gave a hilarious keynote talk where he mentioned homeopathic code optimizations. If you haven’t watched it yet, go watch it now.
For those that haven’t watched the video,
here’s the idea:
he talks about a program dilute.rb
,
that takes another ruby program and “dilutes” it
by replacing characters with whitespace.
So if this is the original program:
…we run dilute.rb
on it:
…it “dilutes” the program
by randomly replacing
40% of the characters with whitespace
(the D=40
env variable sets the percentage),
so you might see something like this:
But when you pipe the output to ruby like this:
…it “remembers” the original program and works perfectly. WHAT? What kind of black magic is this? Aaron doesn’t tell us.
I never figured it out myself, but recently, I came across this gist by @radarek that finally shed some light on the magic behind this:
The important part here
is the $stdout.tty?
method call.
This uses the IO#tty?
method
to determine if the output is a terminal
or a program.
It “dilutes” the text
only if the output is a terminal.
When we pipe the output to ruby,
it detects that the output isn’t a terminal
so it pipes the original text from fib.rb
.
The more time I’ve spent trying to understand Ruby, the less magic it seems to have. So it’s nice to come across something that left me completely baffled and left me thinking, “how could that even work?”.
This was a perfect code demo for a conference called “Keep Ruby Weird”. That we have a conference with that name is what makes the Ruby community so much fun. ;)
Stay weird, and happy hacking!