Forum: Ruby on Rails Create nested hash from array of objects

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
northband (Guest)
on 2009-02-20 03:55
(Received via mailing list)
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.


[#<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

Thanks for any help!
Rick (Guest)
on 2009-02-20 06:03
(Received via mailing list)
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.
northband_101 (Guest)
on 2009-02-20 07:06
(Received via mailing list)
Nice - thanks for the tip.  I got this working great now.
This topic is locked and can not be replied to.