Ruby,创建没有现有键值的数组 [英] Ruby, create array without key values from existing one
本文介绍了Ruby,创建没有现有键值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[{price=> 123,量=> 987},{price=> 432,量=> 13}]
我想创建哈希数组作为;
[[123,987],[432,13]]
我试过 pluck
和 hash.map(&:first ).map(& ;; last)
我无法实现我尝试做的事。
<您可以通过使用 Hash#values
:
array_of_hash_objects = [{price=> 123,量=> 987},{price=> 432,量=> 13}]
p array_of_hash_objects.map(&:values)
#[[123,987],[432,13]]
如果使用Rails,那么我猜你可以使用pluck,但传递所需的属性值,可能是价格和金额:
Model.query.pluck(:price,:amount)
注意查询是您用来获取数据的方法。
I have an array of hashes as;
[{"price" => "123", "amount" => "987"}, {"price" => "432", "amount" => "13"}]
I would like to create array of hashes as;
[["123", "987"], ["432", "13"]]
I have tried pluck
and hash.map(&:first).map(&:last)
I could not achieve what I try to do.
解决方案
You can access the key values in each hash by using Hash#values
:
array_of_hash_objects = [{"price" => "123", "amount" => "987"}, {"price" => "432", "amount" => "13"}]
p array_of_hash_objects.map(&:values)
# [["123", "987"], ["432", "13"]]
If using Rails, then I guess you can use pluck but passing the needed attribute values, maybe price and amount:
Model.query.pluck(:price, :amount)
Note query is the method you're using to get the data.
这篇关于Ruby,创建没有现有键值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文