The need to know Ruby
Posted on 22 February 2008 by Robin FisherAs part of the development of my app, I had a need to display various different categories of to-do items – complete, overdue and “normal”.
I was using a method in the Todo class similar to the following to create these categories:
def self.find_overdue
overdue = Array.new
items = find(:all)
for item in items
if item.overdue?
overdue << item
else
end
end
overdue
end
I was reading through the online Ruby documentation on another issue and came across a nice method in the Hash class: reject. This acts as a “delete if” method and can substantially reduce the code above:
def self.find_overdue
items = find(:all)
items.reject { |i| i.not_overdue? }
end
The “not_overdue” method is defined separately in the Todo class. I think this definitely shows the importance of knowing the Ruby language and equally demonstrates its power.