建立一个日期的倒置数组



我给出了这样的日期列表:

['2020-02-01', '2020-02-05', '2020-02-08']

我想要这个范围的倒数(该范围中缺少的日期(:

['2020-02-02', '2020-02-03', '2020-02-04', '2020-02-06', '2020-02-07']

我确信我可以构建某种循环,从第一个日期开始,然后遍历以构建第二个数组。有没有可能有一个ruby方法/技巧可以更快地做到这一点?

您可以在Date对象的范围内使用Array#difference或Array#-。例如,使用Ruby 2.7.1:

require "date"
dates = ['2020-02-01', '2020-02-05', '2020-02-08']
# convert sorted strings to date objects
dates.sort.map! { Date.strptime _1, "%Y-%m-%d" }
# use first and last date to build an array of dates
date_range = (dates.first .. dates.last).to_a
# remove your known dates from the range - dates).map &:to_s
(date_range - dates).map &:to_s
#=> ["2020-02-02", "2020-02-03", "2020-02-04", "2020-02-06", "2020-02-07"]

为了简洁起见,假设dates中的日期字符串已经排序,您也可以使用这样的火车残骸:

((dates[0]..dates[-1]).to_a - dates).map &:to_s
require 'date'
arr = ['2020-02-26', '2020-03-02', '2020-03-04']
first, last = arr.map { |s| Date.strptime(s, '%Y-%m-%d') }.minmax
#=> [#<Date: 2020-02-26 ((2458906j,0s,0n),+0s,2299161j)>,
#    #<Date: 2020-03-04 ((2458913j,0s,0n),+0s,2299161j)>] 
(first..last).map { |d| d.strftime('%Y-%m-%d') } - arr 
#=> ["2020-02-27", "2020-02-28", "2020-02-29", "2020-03-01",
#    "2020-03-03"]

请参阅日期::strptime和日期#strftime

您可以使用Array#min、Array#max和Array#-轻松解决此问题:

dates = ['2020-02-01', '2020-02-05', '2020-02-08']
missing_dates = ((dates.min..dates.max).to_a) - dates
=> [‘2020-02-02’, ‘2020-02-03’, ‘2020-02-04’, ‘2020-02-06’, ‘2020-02-07’]

最新更新