# Create nested hash from array of objects

**URL:** <https://www.ruby-forum.com/t/create-nested-hash-from-array-of-objects/160824>\
**Category:** Rails\
**Created:** [February 20, 2009, 2:55am UTC](https://www.ruby-forum.com/t/create-nested-hash-from-array-of-objects/160824 "2009-02-20T02:55:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![northband](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/ecae2f/32.png) [@northband](https://www.ruby-forum.com/u/northband)\
**Post date:** [February 20, 2009, 2:55am UTC](https://www.ruby-forum.com/t/create-nested-hash-from-array-of-objects/160824/1 "2009-02-20T02:55:40Z")

</div>

Hi -

What is the best way to create a nested hash from an array of objects?

Here’s what I’m trying to do, take my array of objects and use the  
attribute ‘position’ as a key for each nested hash. The nested hash  
will contain the other array attributes.

Example:

[#\<Spec id: 4057, position: 1, name: “Tonnage”, english\_unit: “T”,  
metric\_unit: “t”\>,  
[#\<Spec id: 4058, position: 2, name: “Spindle”, english\_unit: “T”,  
metric\_unit: “t”\>]

This is what I want to end up with from the above:

{1 =\> {:name =\> “Tonnage”, :english\_unit =\> “T”, :metric\_unit =\> “t”},  
2 =\> {:name =\> “Spindle”, :english\_unit =\> “T”, :metric\_unit =\> “t”}}

I’ve tried different methods of enumerating but can’t quite get what I  
want.

Thanks for any help!

---

<div class="post-metadata">

**Author:** ![northband](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/ecae2f/32.png) [@northband](https://www.ruby-forum.com/u/northband)\
**Post date:** [February 20, 2009, 5:03am UTC](https://www.ruby-forum.com/t/create-nested-hash-from-array-of-objects/160824/2 "2009-02-20T05:03:21Z")

</div>

Looks like you’re starting with ActiveRecord’s so you could possibly  
take advantage of:

spec\_hash = Spec.find(4057).attributes

and glue something together.

---

<div class="post-metadata">

**Author:** ![northband](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/ecae2f/32.png) [@northband](https://www.ruby-forum.com/u/northband)\
**Post date:** [February 20, 2009, 6:06am UTC](https://www.ruby-forum.com/t/create-nested-hash-from-array-of-objects/160824/3 "2009-02-20T06:06:34Z")

</div>

Nice - thanks for the tip. I got this working great now.
