views:

109

answers:

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]]

+4  A: 

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... ;)

Mladen Jablanović
Works.Would have been even more awesome if it were to have worked with Ruby 1.8.6
Shreyas Satish
To make this (or anything else that works in 1.8.7) work in Ruby 1.8.6: `require 'backports'`
Marc-André Lafortune