创建另一个数组中项目之间差异的数组
Creating an array of the difference between items in another array
我的目标是创建一个整数数组,每个整数代表两个日期之间经过的天数。最终我会对其进行平均并进行其他操作。
我已经达到工作代码:
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 and 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")
.)
我的目标是创建一个整数数组,每个整数代表两个日期之间经过的天数。最终我会对其进行平均并进行其他操作。
我已经达到工作代码:
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 and 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")
.)