happiness (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) (^_^) happiness

【Rails】【Ruby】[{key: "A", value: 1},... ]な配列を{ A: 1, B: 2 }にする方法

ハッシュの配列でkeyが一意なときに、Hash化したいとき、あると思います。

RailsActiveRecordで使いました。

# Post belongs_to User

Post.all.select("user_id, count(user_id) as count")
  .group(:user_id)
  .map { |h|  [h[:user_id], h[:count] }
  .to_h

# => { 1: 3, 2: 4, ... }

もっと良い方法求め中です

How to convert hashes array to hash

とかいうタイトルでStackOverflowにありそうでなかった。