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)
Written by James Huynh
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#