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开发者_Go百科 comparable interface in Java, so every time I called sort on User object it will do sort on the predefined attributes.
Thanks,
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
.
精彩评论