Last active
January 20, 2017 00:49
-
-
Save redconfetti/e0d12aef119ad62ef0d2 to your computer and use it in GitHub Desktop.
Convert Array to Indexed Hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Often you'll have an array of hashes, and you find yourself needing to | |
# retrieve an object from that array by some unique attribute of the hash. | |
# | |
# Here is a way to convert an array to a hash that contains hashes indexed by the key value you specify. | |
# This is possible because Array uses the Enumerable module as a mixin | |
users = [ | |
{'id' => 1, 'name' => 'Susan'}, | |
{'id' => 2, 'name' => 'Pat'}, | |
{'id' => 3, 'name' => 'Jason'} | |
] | |
search_user_hash = users.inject({}) { |map, user| map[user['id']] = user; map} | |
# search_user_hash = { | |
# 10932=>{"id"=>10932, "name"=>"Joe"}, | |
# 10936=>{"id"=>10936, "name"=>"Susan"}, | |
# 10943=>{"id"=>10943, "name"=>"Dan"} | |
# } | |
# joe = search_user[10932] | |
# susan = search_user_hash[10943] |
Yeah I'm definitely confused about what is going on here.
Does not seem to work everywhere as expected...:
search_user_hash = users.inject({}) { |map, user| map[user['id']] = user; map}
=> {1=>{"id"=>1, "name"=>"Susan", 2=>{"id"=>2, "name"=>"Pat", 3=>{"id"=>3, "name"=>"Jason"}}},
2=>{"id"=>2, "name"=>"Pat", 3=>{"id"=>3, "name"=>"Jason"}},
3=>{"id"=>3, "name"=>"Jason"}}
perhaps you want this:
users = [{"id"=>1, "name"=>"Susan"}, {"id"=>2, "name"=>"Pat"}, {"id"=>3, "name"=>"Jason"}]
# => [{"id"=>1, "name"=>"Susan"}, {"id"=>2, "name"=>"Pat"}, {"id"=>3, "name"=>"Jason"}]
users.group_by{|x| x["id"]}
# => {1=>[{"id"=>1, "name"=>"Susan"}], 2=>[{"id"=>2, "name"=>"Pat"}], 3=>[{"id"=>3, "name"=>"Jason"}]}
@jemminger, yeah. You're right. My example output was off. I fixed it.
@LeFnord - Yeah. That's a nice approach too, but if you know that the 'id' is unique, then you can avoid working with arrays when accessing the resulting hash by ID.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't the example:
be this?