Demystifying @tenderlove's homeopathic code optimizations
For those that haven’t watched the video,
here’s the idea:
he talks about a program
that takes another ruby program and “dilutes” it
by replacing characters with whitespace.
So if this is the original program:
dilute.rb on it:
…it “dilutes” the program
by randomly replacing
40% of the characters with whitespace
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
$stdout.tty? method call.
This uses the
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
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!