Ugly Ruby

Mike McCabe
2 min readFeb 1, 2016

--

I like Ruby. It’s a pleasant language to code in and review most of the time. But I was reading a post about some Ruby oddities that had some “interesting” ways to do certain things. Based on that I wanted to create some ugly and inscrutable Ruby.

$-_=’=’;@@_=->(_){_*100};@@_.[]($-_);

To break this down I’ll list out the various parts of the code.

  • $-_ is a global variable with the name of -_
  • = is the assignment operator
  • The value of ‘=’ is assigned to ‘$-_’
  • ; is a separator between code expressions
  • @@_ is a class variable with the name ‘_’
  • ->(_){_*100} is a lambda that accepts a variable ‘_’ then multiplies it by 100
  • @@_.[]($-_) this call the lambda with ‘.[]’ and passes the value of ‘$-_’ which is ‘=’
  • ; to end the code block
  • Finish!

So, what’s it do? Nothing really. Without the final ‘;’ it would print ‘=’ 100 times. With ‘;’ it prints nothing. I wanted to get the code down to no alphanumeric characters. I needed something simple to generate a number to multiple with. At first I thought of trying to shell out and get the return status of the last bash command with $? but using `` to exec returned an error of command not found. Then I tried $$ to get the PID of the Ruby code as it was running but same result. Then I had a duh moment and realized I could just use $$ inside of Ruby to accomplish the same thing. So the final code looks like this:

$-_=’=’;@@_=->(_){_*$$};@@_.[]($-_);

Now instead of multiplying $-_ by 100 it multiplies it by the PID of the code running.

What have I accomplished? Nothing but it was interesting to write some very ugly Ruby code when you try to write clean code otherwise. Ruby does lend itself to very clean and understandable code but that doesn’t mean it can’t be ugly.

Here is a more readable version of the code:

#assign "=" to char
char = “="
#get PID of process
pid = $$
#create lambda that does the multiplication
lamb = ->(var){var * pid}
#call the lambda with the char
lamb.call(char)

Thanks to Ernie Miller for a review of this post.

--

--

Mike McCabe

Mike McCabe is a security consultant and researcher. He is the founder of MBM Consultants. mbmconsultants.co