Enumerable#sort
December 12th, 2007 Posted in ActiveRecord, Rails, RubyIn Ruby, to sort a collection of Objects, the <=> method needs to be defined. Suppose we have the following:
# has a field created_at, which is a datetime class Event < ActiveRecord::Base end
Let’s say we want to do the following:
@events = Event.find(:all) @events.sort
To do this, we would need to define the <=> method in Event:
class Event < ActiveRecord::Base
def <=>(event)
created_at <=> event.created_at
end
end
By created a <=> method for Event objects, the Enumerable#sort method now knows which value to sort on; rather, in this example, by elegantly delegating the sorting to some magic Time comparison methods in Ruby that we don’t need to know about.