LoginSignup
3
3

More than 5 years have passed since last update.

Rubyで2次元配列をハッシュに変換するときキーが重複していたら値を足したい

Posted at

文章にするとわけわからんけど要は、Rubyでこのを2次元配列を


[[tanaka, 1], [yamada, 2], [sato, 3], [tanaka, 4]]

こう変換したいとき


{
  "tanaka": 5,
  "yamada": 2,
  "sato": 3
}

どうするかという話。

結果は簡単でeach_with_objectを使えば終わり。


arr = [[tanaka, 1], [yamada, 2], [sato, 3], [tanaka, 4]]
arr.each_with_object(Hash.new(0)) {|(k, v), h| h[k] += v}

1行でできるのすごい。

元ネタ

3
3
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
3
3