Reputation: 16226
Ruby has a sort_by method on Enumerables. Fantastic! So you can do something like
entries.sort_by { |l| l.project.name }
That would sort a bunch of entries by their project names. How could you work it so that within projects that had the same name, entries were sorted by their time?
Upvotes: 13
Views: 3659
Reputation: 40005
Return an array:
entries.sort_by { |l| [ l.project.name, l.project.time] }
this works because the <=>
operator on arrays does a field-by-field 'lexical' comparison which is what you're looking for.
Upvotes: 3
Reputation: 29872
I would suggest putting the column you want to sort by into an array.
entries.sort_by { |l| [l.project.name, l.project.time] }
This will respect the natural sort order for each type.
Upvotes: 26
Reputation: 544
You can use the regular sort method to do it.
entries.sort do |a, b|
comp = a.project.name <=> b.project.name
comp.zero? ? (a.project.time <=> b.project.time) : comp
end
Upvotes: 6