Friday, June 29, 2012

How to create two-dimensional array of Date class for each months (2)

(continued from phosphorescence: How to create two-dimensional array of Date class for each months (1))

If we want to create two-dimensional array for each "year and month", there are 2 ways.

gourp_by with explicit block

require 'date'
begin_day = Date.new(2011, 12, 1)
end_day = Date.new(2012, 2, -1)
hash_each_month = (begin_day..end_day).group_by{|d| [d.year, d.month]} # hash
days_each_month = (begin_day..end_day).group_by{|d| [d.year, d.month]}.values # two-dimensional array

Add method to Data class by open-class

require 'date'

class Date
  def year_month
    [self.year, self.month]
  end
end

begin_day = Date.new(2011, 12, 1)
end_day = Date.new(2012, 2, -1)
hash_each_month = (begin_day..end_day).group_by(&:year_month) # hash
days_each_month = (begin_day..end_day).group_by(&:year_month).values # two-dimensional array

No comments:

Post a Comment