0

私はRubyを初めて使用しyear_ranges、次の配列から生成することができました(これに適切な用語がある場合は修正してください)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"
]

メソッドを作成するにはどうすればよいmonth_rangesので、このような配列を取得できますか?

[
  "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",
  .....
]

助けてくれる人に感謝します。

4

1 に答える 1

6

毎年、毎月、そのようなエントリが 1 つ必要になると思います。

  • Date.new(year, month, 1)指定された年と月  の最初の日を返します
  • Date.new(year, month, -1)指定された年と月の最後の日を返します

これはうまくいくはずです:

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"]
于 2013-09-24T14:01:13.553 に答える