For example, I would like to sort by game_date, and then if the date is the same, sort it by team? What would be the best way to do this?
@teams = @user.teams @games = @teams.reduce([]) { |aggregate, team| aggregate + team.games}.sort_by(&:game_date)
The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.
You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)
The Array#sort method in Ruby uses the venerable Quicksort algorithm. In its best case, Quicksort has time complexity O(n log n), but in cases where the data to be sorted is already ordered, the complexity can grow to O(n2).
The best way would be to have your database do it, but if you want to use Ruby:
@games = @data.sort_by {|x| [x.game_date, x.team] }
The sorting behaviour of Array
is to sort by the first member, then the second, then the third, and so on. Since you want the date as your primary key and the team as the second, an array of those two will sort the way you want.
@teams = @user.teams @games = @teams.games.order("game_date ASC, team ASC")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With