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?
1.
Assuming rank is numeric:
This is just specifying that we compare a and b using
[:rank].2.
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:
Then you can do:
If you include Comparable, it will provide the other comparison operators too.