How to convert Object to array of hashes with symb

2019-08-30 14:33发布

问题:

I am trying:

Product.first.attributes.map{|k, v| "#{k.to_sym} => #{v}"}

However, I receive the output as follows:

["id => 53", "name = blah"], ["id => 54", "name = blahblah"]

What I want is:

[{:id=>53,:name=>"blah"}, {:id=>54,:name=>"blahblah"}]

回答1:

Looks like you're just trying to convert the Product.first.attributes Hash to a Hash with symbols for keys rather than strings. You can make it easy on yourself by calling the symbolize_keys that Rails (ActiveSupport actually) has patched into Hash:

h = Product.first.attributes.symbolize_keys

When you say this:

"#{k.to_sym} => #{v}"

you're just producing a string that looks sort of like a Hash and that's not terribly useful. If you want to symbolize the keys the long way, you'd probably produce an array of arrays using:

...map { |k, v| [ k.to_sym, v ] }

and then feed that whole thing to Hash[]:

h = Hash[Product.first.attributes.map { |k, v| [ k.to_sym, v ] }]

I wouldn't bother with all that noise though, just use symbolize_keys and move on to more interesting problems.