我想知道是否有办法找到日期序列切换的值。
例如,我有一个这样的数组:
[" 2005-12-31"" 2006-12-31"" 2007-12-31"" 2008-12 -31"" 2006-12-31"" 2007-12-31"]
所有日期都从2005年转移到2007年,然后再转换到2006年再开始。当发生这种情况时,我需要开始写一个新的行,但是不能找到一种方法来监视它并告诉我的脚本此时移动到一个新行。
谢谢!
答案 0 :(得分:0)
可以编写一个方法,该方法返回序列中断的索引数组(回归到较旧的年份并打破升序):
def sequence_break_points(arr)
change_points = []
arr.each_with_index do |e, idx|
next if idx == 0
change_points << idx if (e < arr[idx-1])
end
change_points
end
在这种情况下,您可以按如下方式使用该方法:
arr = ["2005-12-31","2006-12-31","2007-12-31","2008-12-31","2006-12-31","2007-12-31"]
years_arr = arr.map { |date| date.split("-").first.to_i }
sequence_break_points(years_arr)
=> [4]
# This is the point in the array where the sequence broke.
# The results of this method can be used to tell the script
# when to start a new line
我确信有更好的方法可以做到这一点,但我相信这样可以完成工作。
希望它有所帮助!