Ruby Flare

Your awesome Tagline

57 notes

Sorting custom objects

To sort custom objects, in the class of the object include the Comparable module and then define the comparable operator:

class Person
  include Comparable

  # name is a string attribute

  def <=> (other_person)
    self.name <=> other_person.name
  end
end

This then lets you do the following to sort person objects by each person’s name:

people.sort

(Source: engineyard.com)

Filed under ruby sorting comparable

  1. rubyflare posted this