Last Updated: February 25, 2016
·
6.765K
· jameshuynh

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)