我正在使用Rails构建时间表应用程序,我需要按时间排序一些记录,但是我希望开始时间为05:00而不是00:00
我的查询看起来像这样:
@ timetable_entries.order(出发时间::asc)
结果:
00:30
03:30
05:30
...
但是我希望从凌晨5点开始,所以生成的数据应如下所示:
05:30
00:30
03:30
有人知道这样做的干净方法吗?
提前感谢。
最简单的方法可能是编写自己的比较器。 ruby sort
方法可以使用一个块(documentation here),该块使您可以使用自定义比较方法进行排序。您可以使用该方法指示5:00早于0:00到4:59的所有时间。
代码看起来像:
@timetable_entries.sort do |time1, time2|
# your custom comparison here
end
arr = %w| 00:30 03:30 00:01, 05:30 10:20 02:10 14:05 19:06 |
#=> ["00:30", "03:30", "00:01,", "05:30", "10:20", "02:10", "14:05", "19:06"]
sorted = arr.sort
#=> ["00:01,", "00:30", "02:10", "03:30", "05:30", "10:20", "14:05", "19:06"]
idx = sorted.find_index { |s| (s <=> '05:30') >= 0 }
#=> 4
sorted.rotate(idx)
#=> ["05:30", "10:20", "14:05", "19:06", "00:01,", "00:30", "02:10", "03:30"]
请参见Array#find_index,String#<=>和Array#rotate。
另一种方法。
arr.sort_by { |s| (s <=> '05:30') == -1 ? "#{s[0,2].to_i+24}:#{s[2,3]}" : s }
如果s = '02:10'
,
s <=> '05:30' #=> -1
a = s[0,2] #=> "02"
b = a.to_i #=> 2
c = b+24 #=> 26
d = s[2,3] #=> ":10"
"#{c}:#{d}" #=> "26::10"