Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby sort_by twice

Tags:

ruby

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?

like image 859
Daniel Avatar asked Sep 18 '09 04:09

Daniel


People also ask

How do you sort an array of numbers in Ruby?

You can use sort_by with a block, and one argument, to define one attribute for each object which is going to be used as the basis for sorting (array length, object attribute, index, etc.). The block should return an integer value which determines the position of the object in the sorted array.

Can you sort elements in a Ruby hash object?

Sorting Hashes in Ruby To sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.

How does sort work 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.


1 Answers

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.

like image 117
brianegge Avatar answered Sep 30 '22 19:09

brianegge