Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort in ruby/rails on two fields?

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) 
like image 258
Kamilski81 Avatar asked Feb 04 '12 18:02

Kamilski81


People also ask

How do you sort objects in Ruby?

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.

How do you sort numbers in Ruby?

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)

What sort does Ruby use?

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).


2 Answers

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.

like image 144
Daniel Pittman Avatar answered Sep 22 '22 06:09

Daniel Pittman


@teams = @user.teams @games = @teams.games.order("game_date ASC, team ASC") 
like image 44
ceth Avatar answered Sep 24 '22 06:09

ceth