captured sparks

Live from Stevenage, England
22 February, 2008

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:

1
2
3
4
5
6
7
8
9
10
11
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:

1
2
3
4
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.


Comments

There are no comments yet. Why not be the first?

Leave a comment