Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4616

Convert Array of objects to Hash with a field as the key

$
0
0

I have an Array of objects:

[  #<User id: 1, name: "Kostas">,  #<User id: 2, name: "Moufa">,  ...]

And I want to convert this into an Hash with the id as the keys and the objects as the values. Right now I do it like so but I know there is a better way:

users = User.all.reduce({}) do |hash, user|  hash[user.id] = user  hashend

The expected output:

{  1 => #<User id: 1, name: "Kostas">,  2 => #<User id: 2, name: "Moufa">,  ...}

Viewing all articles
Browse latest Browse all 4616

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>