66
39

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 1 year has passed since last update.

Rails でオブジェクトの配列を簡単にハッシュ化したい

Last updated at Posted at 2013-06-14

例えば、User モデルの一覧を取得して、
User の name を key、オブジェクトを value とした hash を作りたいとします。

その場合、例えば以下のように実装しますよね。

User.all.inject({}) { |hash, user| hash[user.name] = user; hash }
# => {"美樹さやか"=>#<User id: 1,...>, "佐倉杏子"=> #<User id: 2,...">, "巴マミ"=>#<User id: 3,...>}

これをもっとエレガントに書けるんです。 …そう、Enumerable#index_by ならね。

User.all.index_by { |user| user.name }
# => {"美樹さやか"=>#<User id: 1,...>, "佐倉杏子"=> #<User id: 2,...">, "巴マミ"=>#<User id: 3,...>}

User.all.index_by(&:name)  
# => {"美樹さやか"=>#<User id: 1,...>, "佐倉杏子"=> #<User id: 2,...">, "巴マミ"=>#<User id: 3,...>}

ただし、Enumerable#index_by は Rails (ActiveSupport) が追加しているメソッドなので、
デフォルトの Ruby では使えません…

(参考) https://api.rubyonrails.org/classes/Enumerable.html#method-i-index_by

66
39
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
66
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?