Ruby Array to Histogram: How to group numbers by range?

Viewed 4616

I'm trying to group an array of integers into an hash based on where the individual values fall in a range. Basically I want to convert an array to a fixed-width histogram.

Example:

values = [1,3,4,4,4,4,4,10,12,15,18]
bin_width = 3

I need to group the array values into a range-based historgram by where they fall into a 3-unit wide bucket like so:

{'0..2'=>[1,3],'3..5'=>[4,4,4,4,4],'6..8'=>[],'9..11'=>[10]....

Is there a simple one line solution ( maybe something like values.group_by{|x| #range calc}) that would work here?

2 Answers
Related