2

我有以下数组

t = [
  {nil => 1, 10 => 2, 16 => 4, 5=> 10},
  {nil => 9, 5 => 2, 17 => 3, 10 => 2},
  {10 => 4, 5 => 9, 17 => 1}
]

我怎样才能得到这个结果?

{nil => [1,9,0],10 => [2,2,4], 16 => [4,0,0], 5 => [10,2,9], 17=>[0,3,1]}

我已经看到我可以使用这样的东西

t.group_by{|h| h['key']}

但我不确定是否可以将正则表达式放在括号内

提前致谢

哈维尔

编辑:

只是想按数组内每个散列的每个键进行分组,如果键不存在,则该散列的值为 0

4

3 回答 3

2

这个难以辨认怎么办:

t = [
  {nil => 1, 10 => 2, 16 => 4, 5=> 10},
  {nil => 9, 5 => 2, 17 => 3, 10 => 2},
  {10 => 4, 5 => 9, 17 => 1}
]

# Create hash of possible keys
keys = t.reduce({}) { |m, h| h.each_key { |k| m[k] = [] }; m }

# Iterate through array, for each hash, for each key, append the 
# value if key is in hash or zero otherwise
t.reduce(keys) { |m, h| m.each_key { |k| m[k] << (h[k] || 0) }; m }

puts keys
#=> {nil=>[1, 9, 0], 10=>[2, 2, 4], 16=>[4, 0, 0], 5=>[10, 2, 9], 17=>[0, 3, 1]}
于 2012-08-03T21:29:16.080 回答
1

我不认为有任何可用的功能刚刚尝试了哈希

  def do_my_work(data) 
    hash = {}
    #get all keys first 
    arr.map{|m| m.keys}.flatten.uniq.each {|a| hash[a]=[]}
    # Now iterate and fill the values
    arr.each do |elm|
      hash.each do |k,v|
        hash[k] << (elm[k].nil? ? 0 : elm[k])
      end
    end
  end   

  hash = do_my_work(t)

  puts hash
  # => {nil=>[1, 9, 0], 10=>[2, 2, 4], 16=>[4, 0, 0], 5=>[10, 2, 9], 17=>[0, 3, 1]} 
于 2012-08-03T20:50:38.263 回答
1

不是我写过的最优雅的代码,但它可以完成工作并且易于理解:

def jqq(a)
  keys = []
  result = {}

  a.each do |h|
    keys += h.keys
  end

  keys.uniq.each do |key|
    result[key] = []
    a.each do |h|
      h.default = 0
      result[key] << h[key]
    end
  end

  result
end

t = [
  {nil => 1, 10 => 2, 16 => 4, 5=> 10},
  {nil => 9, 5 => 2, 17 => 3, 10 => 2},
  {10 => 4, 5 => 9, 17 => 1}
]

puts jqq(t)
# {nil=>[1, 9, 0], 10=>[2, 2, 4], 16=>[4, 0, 0], 5=>[10, 2, 9], 17=>[0, 3, 1]}
于 2012-08-03T21:01:05.250 回答