You can do that by defining the <=>
method for your objects. That way, you should be able to just say: collection.sort
for non-destructive sort, or collection.sort!
for in-place sorting:
So, example here:
class A
def <=>(other)
# put sorting logic here
end
end
And a more complete one:
class A
attr_accessor :val
def initialize
@val = 0
end
def <=>(other)
return @val <=> other.val
end
end
a = A.new
b = A.new
a.val = 5
b.val = 1
ar = [a,b]
ar.sort!
ar.each do |x|
puts x.val
end
This will output 1
and 5
.