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