GhostRider GhostRider - 4 months ago 10
Ruby Question

Ruby: group an array of integers in a hash of ranges and counts

I have an array of integers like this:

[1, 1, 1, 2, 2, 4, 4, 5, 6, 11, 11, 12, 15, 22, 23, 23, 23, 31, 32, 32]


I am trying to convert this to a hash, grouping according to ranges at intervals of 10....

So, in this case it would be

{ [1..10] => 9, [11..20] => 4, [21..30] => 4, [31..40] => 3 }

I have tried a few things which haven't come close so it's a bit pointless putting them down here. I can convert the array to ranges

[1, 1, 1, 2, 2, 4, 4, 5, 6, 11, 11, 12, 15, 22, 23, 23, 23, 31, 32, 32].sort.uniq.inject([]) do |spans, n|
if spans.empty? || spans.last.last != n - 1
spans + [n..n]
else
spans[0..-2] + [spans.last.first..n]
end
end


But this is not what I am looking for. Any suggestions (even pointing me in the right direction) would be appreciated.

Answer
Hash[
  your_array.group_by{|i| i / 10}.map{|k,v|
    [(k*10+1..(k+1)*10), v.count]
  }
]
#=> {1..10=>9, 11..20=>4, 21..30=>4, 31..40=>3}
Comments