Skip to content

Instantly share code, notes, and snippets.

@warolv
Created November 3, 2013 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warolv/7292030 to your computer and use it in GitHub Desktop.
Save warolv/7292030 to your computer and use it in GitHub Desktop.
Rails’ index_by: the easy way to convert an Array to a Hash
Post.all.index_by { |post| post.id }
# => { 1 => #<Post ...>, 2 => #<Post ...>, ... }
Post.all.index_by(&:title)
# => { "My first post" => #<Post ...>, "My second post" => #<Post ...>, ... }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment