Friday, February 15, 2008

Tip of the day

I recently was working some OPC, that is, Other People's Code. It's always entertaining, frequently frustrating and usually enlightening. This other persons code wasn't bad; just a tad ugly. With some many people coming to Ruby, it's amazing how they tend to pervert this nice terse language into something that looks like Java. So the code snippet I worked with looked like this:

if gender == 'male'
return '1'
elsif gender == 'female'
return '2'
elsif gender.nil?
return ' '
end

So, what we have here is your basic condition block. First of all, the returns are kind of ugly. Any Ruby developer knows that you should hardly ever have to write returns. Okay, I can get rid of the returns; and, maybe I could use a case statement instead of the same. But it's about the same amount of code.

So I came up with an interesting alternative ... it uses a hash to perform the value translation, and relies on the fact that calling to_s on nil returns an empty string. Here's my one-line solution:

{'male' => '1', 'female' => '2', '' => ' '}[gender.to_s]

Got a comment about this? Let me know ...