How to write "better" Ruby programs
I recently asked
a question on Stackoverflow about when it's best to use a
statement versus using a
in Ruby. I got a few answers including a really good specific answer. But another more general answer really struck me, so I'm sharing it here.
Igor Krivokon wrote
In general, "better" in programming means different things. For example better program
Since we are talking about Ruby, the performance is typically of a lesser concern. If you really need performance, you might consider another programming language. So, I would look at criteria (1) and (2) first. The better looking Ruby code usually represents a "better" program. Which code looks better? Which expresses the intent better? Which would be easier to modify if you add/remove logic? It depends on your problem, and it's a matter of taste, to certain degree.
To me, in your short example, the hash solution is better. The case solution provides more flexibility, which you don't need in this case (but might need in other cases).
- is easier to understand, i.e. expresses the intent better
- is easier to maintain. For example, less lines of code, less error-prone, etc.
- has better performance, in terms of execution time
- has better performance, in terms of memory usage
Igor's answer really helped me prioritize competing needs and easily got my upvote. If you find his answer helpful, I'd suggest you do the same.
10 May 2010