→ Sorting objects in array in Ruby → → →

It's easy to sort a simple array in Ruby, you just do a=[1,3,2]; a.sort. But what if you want to sort array of objects? It's also very simple.

All you have to do is define a spaceship operator. What is spaceship operator? It's this: <=>. It returns three values for A and B. -1 if A<B, 0 if A=B and 1 if A>B.

module Geo
  class Distance
    KM = 'km'
    attr_reader :amount

    def initialize(amount, unit = KM) 
      @amount, @unit = amount, unit

    def <=>(other)
      @amount <=> other.amount


distances = []
distances << Geo::Distance.new(1)
distances << Geo::Distance.new(4)
distances << Geo::Distance.new(2)

To prove that it worked we can display sorted values:

>> distances.sort.map {|d| d.amount}
=> [1, 2, 4]

Created on 15 June 2009