I need to sort a table of objects of type Range
by their start point. For that I have the following code which works fine:
ranges = @ranges.sort do |a,b|
(a.min) <=> (b.min)
end
I was just wondering if there was a shorter and elegant way to do the same thing.
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 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.
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 about:
ranges = @ranges.sort_by(&:min)
Or if you actually mean the starting point rather than the minimum, since ranges such as (5..3)
can exist:
ranges = @ranges.sort_by(&:first)
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