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
Related Q & A:
- Rails: How to use ActionMailer by itself?Best solution by stackoverflow.com
- Is there email validation baked in to Rails 3?Best solution by coverhound.com
- Object reference not set to an instance of an object; null?Best solution by Stack Overflow
- How to solve "Object reference not set to an instance of an object?Best solution by Stack Overflow
- How to sort the Object{} properties?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.