How to sort collection of object?

Sort collection of object in rails?

  • 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,

  • Answer:

    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.

art at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.