Simplifying Your Ruby Code
I used to write Ruby code like this a lot when I my brain was still half .NET.
def is_ready?
if self.status > 3
return true
else
return false
end
end
I see this all the time on the Rails mailing list. Would you be surprised to know that you can write the same method this way:
def ready?
self.status > 3
end
(I’d do away the the magic number “3” in favor of a constant, but I digress…)
Notice two things:
- Methods that return a true/false indicator should end with a question mark. For more on this topic, see my other post on the topic of naming conventions in Ruby.
- Ruby uses the last-evaluated expression as the return value. No need to wrap it with a useless if/else block.
Questions? Got another example of code patterns you’ve seen that could be simpler? Use Textile formatting in the comments.


Recent comments
1 year 23 weeks ago
1 year 23 weeks ago
1 year 25 weeks ago
1 year 27 weeks ago
1 year 42 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 46 weeks ago
1 year 48 weeks ago