Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to sort ranges in ruby

Tags:

ruby

I need to sort a table of objects of type Rangeby 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.

like image 594
Pierre Michard Avatar asked Dec 26 '15 00:12

Pierre Michard


People also ask

What sorting algorithm 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).

How do you sort a method 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 hashes in Ruby?

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.


1 Answers

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)
like image 186
Mori Avatar answered Oct 08 '22 15:10

Mori