Tintin81
Tintin81

Reputation: 10215

How make a date range array in Ruby that starts with the current month?

Thanks to Stefan I was able to create a function that returns a number of date ranges:

def years
  [2013, 2012, 2011, 2010, 2009]
end

def month_ranges
  years.flat_map { |y|
    12.downto(1).map { |m| Date.new(y,m,1)..Date.new(y,m,-1) }
  }
end

# => 

[
  Mon, 01 Dec 2013..Wed, 31 Dec 2013, 
  Sat, 01 Nov 2013..Sun, 30 Nov 2013, 
  Wed, 01 Oct 2013..Fri, 31 Oct 2013, 
  Mon, 01 Sep 2013..Tue, 30 Sep 2013
]

Now, is there a way to make this date array start with the current month of the current year as well? In the following years it should always start with December and end with January.

Thanks to anyone who can help.

Upvotes: 1

Views: 509

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

To provide the result in the format required in the earlier question:

require 'date'
years = [2013, 2012, 2011, 2010, 2009]
years.map(&:to_s).product([*'-01'..'-12'].reverse).map(&:join).select{|d| d <= Date.today.to_s[0..-3]}

=> ["2013-09", "2013-08",..., "2009-01"]

Upvotes: 2

Dan Barron
Dan Barron

Reputation: 1104

Simple answer: check the year against the current year. If they're equal, start with current month, if not start with 12.

years = [2013, 2012, 2011, 2010, 2009]

def month_ranges
  years.flat_map { |y|
    if y == Date.today.year
      start = Date.today.month
    else
      start = 12
    end
    start.downto(1).map { |m| Date.new(y,m,1)..Date.new(y,m,-1) }
  }
end

Upvotes: 2

Related Questions