Hi 大家好,我有这么一组 hash:
{"2014-11-22" => 1, "2014-11-30" => 1, "2015-01-02" => 0, "2015-01-22" => 1}
希望能够按月整理成以下这样,遇到相同的月将 hash 的值相加:
{"2014-11" => 2, "2015-01" => 1}
该如何实现呢?...
tmp = {} {"2014-11-22" => 1, "2014-11-30" => 1, "2015-01-02" => 0, "2015-01-22" => 1}.each do |key, value| tmp["#{key[0,7]}"] = tmp["#{key[0,7]}"].to_i + value end
这样应该可以达到目的
hash2 = {} hash1.each do |k,v| hash2[k[0,7]] ||= 0 hash2[k[0,7]] += v end
hash1.each_with_object({}) { |(k,v), m| m[k[0,7]] = m[k[0,7]].to_i + v }
h.group_by { |k, _| k[0..6] }.map { |k, v| [k, v.map(&:second).sum] }.to_h
3Q LS 的同学们提供思路~~ @king1990_cool @chaucerling @48hour @swordray