从日期列表中创建具有日期范围的哈希数组的最佳方法是什么。例如:如果我有一个数组中的日期列表,如下所示:
['12/11/2014','13/11/2014','14/11/2014','24/11/2014','25/11/2014','26/11/2014',' 27/11/2014','28/11/2014','29/11/2014','04/12/2014','05/12/2014','06/12/2014','07/12/2014','24/12/2014','25/12/2014','26/12/2014','28/12/2014','30/12/2014']
我正在尝试获取日期范围哈希数组,如下所示:
[{:from => '12/11/2014', :to => '14/11/2014'}, {:from => '24/11/2014', :to => '29/11/2014 '}, {:from => '04/12/2014', :to => '07/12/2014'}, {:from => '24/12/2014', :to => '26/12/1014'}, {:from => '28/12/2014', :to => '28/12/2014'}, {:from => '30/12/2014', :to => '30/12/2014'}]
Ruby 中有什么可以生成这样的东西吗?谢谢。
最佳答案
Enumerable 有 slice_before
方法,它可以做你想做的事,加上一些额外的代码。这是来自 the documentation :
If the block needs to maintain state over multiple elements, local variables can be used. For example, three or more consecutive increasing numbers can be squashed as follows:
a = [0, 2, 3, 4, 6, 7, 9]
prev = a[0]
p a.slice_before { |e|
prev, prev2 = e, prev
prev2 + 1 != e
}.map { |es|
es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
}.join(",")
#=> "0,2-4,6,7,9"
显然这不是完整的答案,但我的计算机上没有可以完全满足您要求的代码。
关于ruby - 使用 ruby 从日期列表创建日期范围数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26901650/