captured sparks

The need to know Ruby

As 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.

You can talk to me, or trackback from your own site. Or, if you're looking for more things to read? Why not check out the Archive.

Talk to me