根据哈希中的键将值拆分为单独的数组?

时间:2016-02-24 11:55:39

标签: ruby

我有这样的事情

[
  {
    "key": "55ffee8b6a617960010e0000",
    "doc_count": 1
   },
    {
     "key": "55fff0376a61794e190f0000",
     "doc_count": 1
    },
    {
     "key": "55fff0dd6a61794e191f0000",
     "doc_count": 1
    }
]

我想将:key值和:doc_count值分隔为单独的数组,例如

["55ffee8b6a617960010e0000", "55fff0376a61794e190f0000", "55fff0dd6a61794e191f0000"]

[1,1,1]一样。怎么做到这一点?

3 个答案:

答案 0 :(得分:6)

您可以在此处使用transpose

keys, doc_counts = array_of_hashes.map(&:values).transpose

正如D-side所指出的,这取决于每个哈希的键的顺序是相同的。如果您无法确保这一点(例如,您的数据是通过API创建的),则必须执行对哈希键进行排序的附加步骤。这看起来像是:

keys, doc_counts = array_of_hashes.map{|h| Hash[h.sort].values }.transpose

在任何一种情况下,你都会得到类似的东西:

keys # => ["55ffee8b6a617960010e0000", "55fff0376a61794e190f0000", "55fff0dd6a61794e191f0000"]
doc_counts # => [1, 1, 1]

答案 1 :(得分:2)

您可以使用其中一些

a = [
  {
    "key" => "55ffee8b6a617960010e0000",
    "doc_count" => 1
  },
  {
    "key" => "55fff0376a61794e190f0000",
    "doc_count" => 1
  },
  {
    "key" => "55fff0dd6a61794e191f0000",
    "doc_count" => 1
  }
]

1

hash = Hash[a.map { |h| [h["key"], h["doc_count"]] }]
hash.keys
hash.values

2

exp = Hash.new { |k, v| k[v] = [] }
a.map { |h| h.each { |k, v| exp[k] << v } }

3

hash = a.each_with_object({}) { |arr_h, h| h[arr_h["key"]] = arr_h["doc_count"] }
hash.keys
hash.values

答案 2 :(得分:0)

您可以迭代并将其分配给新数组doc_countskeys

array = [{"key"=>"55ffee8b6a617960010e0000", "doc_count"=>1}, {"key"=>"55fff0376a61794e190f0000", "doc_count"=>1}, {"key"=>"55fff0dd6a61794e191f0000", "doc_count"=>1}]
doc_counts, keys = [],[]
array.each do |a|
    doc_counts << a["doc_count"]
    keys << a["key"]
end

结果

>> doc_counts
=> [1, 1, 1]
>> keys
=> ["55ffee8b6a617960010e0000", "55fff0376a61794e190f0000", "55fff0dd6a61794e191f0000"]

doc_counts = []
keys = array.map do |a|
    doc_counts << a["doc_count"]
    a["key"]
end