如何使用符号键将对象转换为哈希数组 [英] How to convert Object to array of hashes with symbol keys

查看:105
本文介绍了如何使用符号键将对象转换为哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆