如何使用符号键将对象转换为哈希数组 [英] How to convert Object to array of hashes with symbol keys
问题描述
我正在尝试:
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"]
我想要的是:
[{:id=>53,:name=>"blah"}, {:id=>54,:name=>"blahblah"}]
推荐答案
看起来您只是想将Product.first.attributes
哈希转换为带有键而不是字符串的符号的哈希.您可以通过调用 symbolize_keys
Rails(实际上是ActiveSupport)已修补到Hash中:
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 ] }
,然后将整个内容输入 Hash[]
:
and then feed that whole thing to Hash[]
:
h = Hash[Product.first.attributes.map { |k, v| [ k.to_sym, v ] }]
我不会打扰所有噪音,只需使用symbolize_keys
并继续处理更有趣的问题即可.
I wouldn't bother with all that noise though, just use symbolize_keys
and move on to more interesting problems.
这篇关于如何使用符号键将对象转换为哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!