【问题标题】:Creating an array of the difference between items in another array创建另一个数组中项目之间差异的数组
【发布时间】:2020-05-14 00:32:46
【问题描述】:

我的目标是创建一个整数数组,每个整数代表两个日期之间经过的天数。最终我会对它进行平均和其他操作。

我已经找到了工作代码:

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 数组有很多方法,所以如果其中一个有更好的解决方案,我不会感到惊讶。

【问题讨论】:

    标签: arrays ruby date-difference


    【解决方案1】:

    您可以使用Enumerable#each_with_objectEnumerator#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
    

    【讨论】:

      【解决方案2】:
      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)

      Enumerable#each_cons

      一个人只能通过书写映射一次

      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")。)

      【讨论】:

        猜你喜欢
        • 2019-06-27
        • 2021-12-06
        • 2021-06-24
        • 1970-01-01
        • 2021-12-05
        • 2022-12-02
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        相关资源
        最近更新 更多