ruby - 通过重复多个哈希的键来分组

时间:2012-08-03 20:04:25

标签: ruby arrays hash

我有以下数组

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

3 个答案:

答案 0 :(得分: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]}

答案 1 :(得分: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]} 

答案 2 :(得分: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]}