代码之家  ›  专栏  ›  技术社区  ›  Valentin V

按周/月/年分组日期散列

  •  2
  • Valentin V  · 技术社区  · 16 年前

    h={
    2010-03-01=>2
    2010-03-02=>4
    2010=03-03=>1
    ..
    ..
    n days with working hours
    }
    

    如果哈希键是一个日期,哈希值是一个整数,我如何将这个哈希转换成一个新的哈希,其中键是周/月/年(加总)?

    h_weeks={7=>36, 8=>42, 9=>34 ..,..,n}
    

    月份:

    h_months={1=>170, 2=>180, 3=>146}
    

    h_years={2009=>950, 2010=>446}
    

    其中key是周数(月/年),value是本周/月/年内工作时间的总和。

    谢谢。

    1 回复  |  直到 14 年前
        1
  •  4
  •   Mladen Jablanović    16 年前
    h = {
      Date.parse('2010-04-02') => 3,
      Date.parse('2010-05-03') => 5,
      Date.parse('2009-04-03') => 6
    }
    by_year = Hash.new(0)
    by_month = Hash.new(0)
    by_week = Hash.new(0)
    h.each{|d,v|
      by_year[d.year] += v
      by_month[d.month] += v
      by_week[d.cweek] += v
    }
    

    或者,稍微有点异国情调:

    aggregates = {}
    h.each{|d,v|
      [:year, :month, :cweek].each{|period|
        aggregates[period] ||= Hash.new(0)
        aggregates[period][d.send(period)] += v
      }
    }
    p aggregates
    #=>{:year=>{2010=>8, 2009=>6}, :month=>{4=>9, 5=>5}, :cweek=>{13=>3, 18=>5, 14=>6}}