我的目标是在整数上创建一个数组,每个数组代表两个日期之间经过的天数。最终,我将求平均值并对其进行其他操作。
我已经找到了工作代码:
require 'date'
dates = ['2020-01-30', '2020-01-24', '2020-01-16'].map { |d| Date.parse(d) }
day_difference = []
dates.each_index do |index|
begin
day_difference.push((dates[index] - dates[index + 1]).to_i)
rescue TypeError # end of array
break
end
end
但是我想知道是否有一种更清洁的方法,而不必注意最后一个索引值。 Ruby数组有很多方法,因此,如果其中之一拥有更好的解决方案,我不会感到惊讶。
您可以使用Enumerable#each_with_object和Enumerator#with_index方法在一个循环中解决它。
dates = ['2020-01-30', '2020-01-24', '2020-01-16']
day_difference = dates.each_with_object([]).with_index do |(date, arr), index|
next if index == dates.size - 1
arr << (Date.parse(date) - Date.parse(dates[index + 1])).to_i
end
require 'date'
dates = ['2020-01-30', '2020-01-24', '2020-01-16']
dates.map { |s| DateTime.strptime(s, '%Y-%m-%d').to_date }.
each_cons(2).map { |d1,d2| (d1-d2).to_i }
#=> [6, 8]
根据需要将(d1-d2)
更改为(d2-d1)
。
一个人只要写一次就可以映射一次
dates.each_cons(2).map { |s1,s2| (DateTime.strptime(s1, '%Y-%m-%d').to_date -
DateTime.strptime(s2, '%Y-%m-%d').to_date).to_i }
但是这样做的缺点是必须将strptime
两次应用于日期字符串的dates.size-2
。
Date#parse仅应在对日期字符串全部采用正确格式的置信度很高的情况下使用(而不是DateTime::strptime
)。 (尝试Date.parse("Parse may work or may not work")
。)