2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyで、hashをmergeするときに、同一keyの場合はvalueを集計したいとき

Last updated at Posted at 2018-07-04

例えば、keyに日付が入っており、valueに値が入っているhashが2つあり、


scores1 = [ {'2018-07-01', 1},   {'2018-07-03', 2},  {'2018-07-04', 3} ]
scores2 = [ {'2018-07-02', 1},   {'2018-07-03', 1},  {'2018-07-05', 2} ]

そのhashを以下のようにマージしたい(同一keyの場合は値を合計したい)場合


sum_score = [{'2018-07-01', 1}, {'2018-07-02', 1},  {'2018-07-03', 3},  {'2018-07-04', 3},  {'2018-07-05', 2} ]

ループ回しながらKeyを判定して・・とかやらなくても、こうすることで簡単にできます。


sum_score = scores1.merge(scores2) do |key, oldval, newval|
    # 同一keyの場合はsumを行う
    oldval + newval
end

同じことで困った人のために、メモとして残しておきます。
配列や連想配列の集計は色々便利なやり方があるようです。

参考URL:
https://ref.xaio.jp/ruby/classes/hash/merge

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?