hc6tba
Last Updated: February 25, 2016
·
1.423K
· jameshuynh
6d16ca5d89fc317247beb1cc6011bad9

Convert Active Record array to indexed hash

I used to do like below every time I want to convert my array of active record into a hash for easier access later on

posts_index_by_id = Post.all.inject({}) do |hash, el|
   hash[el.id] = el
   hash
end
# {1 => #<Post>, 2 => #<Post> ...}

But now, I just found out that there is a better and simple way to do it

posts_index_by_id = Post.all.index_by(&:id)
posts_index_by_title = Post.all.index_by(&:title)
Say Thanks
Respond