在ruby中对范围进行排序的最优雅方法是什么?

时间:2021-01-15 20:19:41

I need to sort a table of objects of type Rangeby their start point. For that I have the following code which works fine:

我需要对Rangeby类型的对象进行排序。为此,我有以下代码可以正常工作:

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.

我只是想知道是否有一种更短更优雅的方式来做同样的事情。

1 个解决方案

#1


9  

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:

或者,如果您实际上是指起点而不是最小值,因为(5..3)等范围可以存在:

ranges = @ranges.sort_by(&:first)

#1


9  

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:

或者,如果您实际上是指起点而不是最小值,因为(5..3)等范围可以存在:

ranges = @ranges.sort_by(&:first)