Hash to array of arrays

Hi,

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?

Thanks,

David

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|
metric.attributes.values
end

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.

That works well.

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

Denver, CO 3 3 1 3 . . .

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?

Aaah!
First, try if this:

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

fits your needs.

(docs at
http://api.rubyonrails.org/classes/ActiveRecord/XmlSerialization.html )

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.