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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
068d5aec7da6333ce34a848ed4867668?d=identicon&s=25 northband (Guest)
on 2009-02-20 02: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.

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!
Af2ce6689213fdb78913a9662b18da6b?d=identicon&s=25 Rick (Guest)
on 2009-02-20 05: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.
068d5aec7da6333ce34a848ed4867668?d=identicon&s=25 northband_101 (Guest)
on 2009-02-20 06: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.