I have an array : keys=[["a","a","b"],["a","b","c"]] I need to find the number of times "a","b","c" occurs in each sub-array of 'keys'.
output could be a hash : ["a"=> [2,1],"b"=>[1,1],"c"=>[0,1]]
I have an array : keys=[["a","a","b"],["a","b","c"]] I need to find the number of times "a","b","c" occurs in each sub-array of 'keys'.
output could be a hash : ["a"=> [2,1],"b"=>[1,1],"c"=>[0,1]]
Perhaps not the fastest, but probably among the shortest:
Hash[
keys.flatten.uniq.map{|e|
[e, keys.map{|ar| ar.count(e)}]
}
]
=> {"a"=>[2, 1], "b"=>[1, 1], "c"=>[0, 1]}
or
keys.flatten.uniq.inject({}){|acc,e|
acc.merge({e => keys.map{|ar| ar.count(e)}})
}
Here's a shot at 1.8.6 version:
keys.flatten.uniq.inject({}){|acc,e|
acc[e] = keys.map{|ar|
ar.select{|c| c==e}.size
}
acc
}
But you'd better get that backports gem soon... ;)