Sorting an array of structs
arrays, ruby-on-rails, sorting, struct
Solution
1.
Assuming rank is numeric:
array.sort {| a, b | a[:rank] <=> b[:rank] }
This is just specifying that we compare a and b using `[:rank]`.
2.
array.sort {| a, b | a[:rank] == b[:rank] ?
a[:user].created_at <=> b[:user].created_at :
a[:rank] <=> b[:rank] }
This uses a ternary. If the ranks are equal, we compare by [:user].created_at. Otherwise, we compare by the ranks.
You could implement <=> in your own class to allow sorting natively:
class Leader < Struct.new(:rank, :user)
def <=>(other)
self[:rank] <=> other[:rank]
end
end
Then you can do:
leaders.sort()
If you include Comparable, it will provide the other comparison operators too.
Problem
I have an array of structs called leaders. The struct class looks like this, for contextual info: ``` class Leader < Struct.new(:rank, :user); end ``` Two questions: - How do I sort the array of structs by rank? - How do I sort the array of structs by rank and by user.created_at?