Tintin81
Tintin81

Reputation: 10207

How to generate an array with month ranges in Ruby?

I am new to Ruby and managed to generate year_ranges (please correct me if there's a better term for this) from an array of years:

class User < ActiveRecord::Base

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


  def year_ranges
    years.map { |y| "#{y}-01-01_#{y}-12-31" }
  end

end

@user.year_ranges 

# => 
[
  "2013-01-01_2013-12-31", 
  "2012-01-01_2012-12-31", 
  "2011-01-01_2011-12-31", 
  "2010-01-01_2010-12-31", 
  "2009-01-01_2009-12-31"
]

Now how can I create a method month_ranges, so I get an array like this?

[
  "2013-01-01_2013-01-31", 
  "2012-02-01_2012-02-31", 
  "2011-03-01_2011-03-31", 
  "2010-04-01_2010-04-31", 
  "2009-05-01_2009-05-31",
  .....
]

Thanks to anybody who can help.

Upvotes: 0

Views: 843

Answers (1)

Stefan
Stefan

Reputation: 114138

I suspect you want one such entry for every month in each year.

  • Date.new(year, month, 1) returns the first day of the given year and month  
  • Date.new(year, month, -1) returns the last day of the given year and month

This should work:

require 'date'

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

years.flat_map { |y|
  12.downto(1).map { |m| "#{Date.new(y, m, 1)}_#{Date.new(y, m, -1)}" }
}
#=> ["2013-12-01_2013-12-31", "2013-11-01_2013-11-30", "2013-10-01_2013-10-31", "2013-09-01_2013-09-30", "2013-08-01_2013-08-31", "2013-07-01_2013-07-31", "2013-06-01_2013-06-30", "2013-05-01_2013-05-31", "2013-04-01_2013-04-30", "2013-03-01_2013-03-31", "2013-02-01_2013-02-28", "2013-01-01_2013-01-31", "2012-12-01_2012-12-31", "2012-11-01_2012-11-30", "2012-10-01_2012-10-31", "2012-09-01_2012-09-30", "2012-08-01_2012-08-31", "2012-07-01_2012-07-31", "2012-06-01_2012-06-30", "2012-05-01_2012-05-31", "2012-04-01_2012-04-30", "2012-03-01_2012-03-31", "2012-02-01_2012-02-29", "2012-01-01_2012-01-31", "2011-12-01_2011-12-31", "2011-11-01_2011-11-30", "2011-10-01_2011-10-31", "2011-09-01_2011-09-30", "2011-08-01_2011-08-31", "2011-07-01_2011-07-31", "2011-06-01_2011-06-30", "2011-05-01_2011-05-31", "2011-04-01_2011-04-30", "2011-03-01_2011-03-31", "2011-02-01_2011-02-28", "2011-01-01_2011-01-31", "2010-12-01_2010-12-31", "2010-11-01_2010-11-30", "2010-10-01_2010-10-31", "2010-09-01_2010-09-30", "2010-08-01_2010-08-31", "2010-07-01_2010-07-31", "2010-06-01_2010-06-30", "2010-05-01_2010-05-31", "2010-04-01_2010-04-30", "2010-03-01_2010-03-31", "2010-02-01_2010-02-28", "2010-01-01_2010-01-31", "2009-12-01_2009-12-31", "2009-11-01_2009-11-30", "2009-10-01_2009-10-31", "2009-09-01_2009-09-30", "2009-08-01_2009-08-31", "2009-07-01_2009-07-31", "2009-06-01_2009-06-30", "2009-05-01_2009-05-31", "2009-04-01_2009-04-30", "2009-03-01_2009-03-31", "2009-02-01_2009-02-28", "2009-01-01_2009-01-31"]

Upvotes: 6

Related Questions