My One-Liner Fetish
When I do codewars exercises, I enjoy looking at the clever solutions submitted by other users. They are often delightfully concise, almost absurdly so. They do in one line what takes me four or five. They take an approach so unexpected and incongruous that I laugh out loud. I said to myself, “I can play this game too”.
So I wrote out insertion sort as concisely as I could. This is as far as I got:
def sort(arr)
arr.each_with_index do |n, index| index.downto (1) do |i| arr[i-1], arr[i] = arr[i], arr[i-1] if n < arr[i-1] end endreturn arrend
I showed off my work on Slack (under the guise of asking for comments) and, predictably, my ego was burst. Apparently, my perverse desire to be as short and concise as possible is not necessarily aligned with the priority of writing good code. For one thing, good code should be readable and concise code, after a point, isn’t.
Yet the perfectionist in me doesn’t want to let go. Maybe it’s because cute code makes me chuckle. Maybe it’s because code is an art form no less than a functional structure. Maybe I’m just a sucker for perfectionism. But I think there’s something worthwhile in doing it, even if it yields “bad code”. It stimulates me to sharpen my knowledge of Ruby, the nuances of its syntax and its built-in objects.
My mentor told me about code golf. If it weren’t for the fact that I need to get a job and earn money, maybe I’d just do those all day…Now that would be perverse.