views:

458

answers:

1

I know I can use something like User.sort {|a, b| a.attribute <=> b.attribute} or User.find and order, but is it a way like comparable interface in Java, so every time I called sort on User object it will do sort on the predefined attributes.

Thanks,

+4  A: 

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.

Geo
I just found that ruby has Comparable module and we can implements all comparison operations with in one method define <=>. Using it just include Comparable in any class you want.
art
It's the same thing. If you include Comparable, you still need to define your own `<=>` method. The thing is, you'll only have one extra line of code, which won't serve to any purpose.
Geo
It does serve some purposes, that is in case you want your Objects to have comparison operations (< <= == >= >). Instead of define it separately, you just include Comparable and define your own <=> method.
art
This is true. However, I was refering to your question alone.
Geo