Forum: Ruby on Rails Hash to array of arrays

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.
David L. (Guest)
on 2007-04-03 02:07

I need to convert this data I pulled from a database:

[#<Metric:0x24fbbec @attributes={"interested"=>"3", "prequalified"=>"3",
"office"=>"Denver, CO", "passed"=>"1", "qualified"=>"3"}>,
#<Metric:0x24fbb10 @attributes={"interested"=>"1", "prequalified"=>"1",
"office"=>"McLean, VI", "passed"=>"1", "qualified"=>"1"}>,
#<Metric:0x24fbae8 @attributes={"interested"=>"1", "prequalified"=>"1",
"office"=>"Raleigh, NC", "passed"=>"1", "qualified"=>"1"}>,
#<Metric:0x24fbac0 @attributes={"interested"=>"1", "prequalified"=>"1",
"office"=>"Troy, MI", "passed"=>"0", "qualified"=>"1"}>]

to this format:

[["3", "3', "Denver, CO", "1", "3"], ["1", "1", "McLean, VI", "1", "1"],
["1", "1", "Raleigh, NC", "1", "1"], ["1", "1", "Troy, MI", "0", "1"]]

I'm a little stuck on how to do this.

Any ideas?


Florian G. (Guest)
on 2007-04-03 02:32
The interesting part of this is that you have an array of objects that
contain a hash! So the question is: how do you extract the hash out of
every object and convert it to an array?

Hash to array -> Hash#values
Collect the results -> Array#collect

result = @metrics.collect do |metric|

The ultra-nice solution would be to write an encoder (like the to_json
stuff) for this, which is left to the reader as an exercise - but this
one does the job good enough.
David L. (Guest)
on 2007-04-03 19:29
That works well.

Ideally, I want to get these values into xml format like:

  <string>Denver, CO</string>

I know who to do it when I get a single array of two values, but I'm not
sure how to iterate over an array of arrays containing multiple values.

Any ideas?
Florian G. (Guest)
on 2007-04-03 20:00
First, try if this:

@metrics.to_xml (it can be called on the whole collection)

fits your needs.

(docs at )

If you want total costumization, i suggest to implement the
to_xml-Method for each model by yourself. There is an info on how to do
this in the doc-page above.
This topic is locked and can not be replied to.