Iterate every month with date objects

后端 未结 9 2172
轻奢々
轻奢々 2021-02-01 05:47

So I have two ruby Date objects, and I want to iterate them every month. For example if I have Date.new(2008, 12) and Date.new(2009, 3), it would yield me 2008-12, 2009-1, 2009-

9条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 06:29

    I have added following method to Date class:

    class Date
      def all_months_until to
        from = self
        from, to = to, from if from > to
        m = Date.new from.year, from.month
        result = []
        while m <= to
          result << m
          m >>= 1
        end
    
        result
      end
    end
    

    You use it like:

    >> t = Date.today
    => #
    >> t.all_months_until(t+100)   
    => [#, #, #, #]
    

    Ok, so, more rubyish approach IMHO would be something along:

    class Month> 1
      end
    end
    

    and

    >> t = Month.today
    => #
    >> (t..t+100).to_a
    => [#, #, #, #]
    

    But you would need to be careful to use first days of month (or implement such logic in Month)...

提交回复
热议问题