The chunk method groups the elements of an enumerable collection by their return value from the given block. This method groups consecutive matching elements together, as you'll see in the examples below.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
Number List
@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8] # chunk by even numbers: [1,3,5,2,4,7,9].chunk{|number| number.even? ? 'even' : 'odd'}.each do |eo_status, list| puts "#{eo_status}: #{list.join('')}" end # output # odd: [1, 3, 5] # even: [2, 4] # odd: [7, 9]
Pet Inventory
# chunking pets by leg count: @inventory.chunk(&:legs).each do |leg_count, pet_list| puts " #{leg_count}: #{pet_list.map(&:name).join(',')}" end # output # 4: dog,cat # 0: fish # 8: scorpion # 6: beetle # 2: monkey # 0: rock
Heroku Log File
# chunking heroku requests by status code: @requests.chunk(&:status).each do |status, records| puts " #{status}: #{records.map(&:id).join(',')}" end # output # 503: 1 # 200: 2,3,4,5,6,7,8,9,10,11,12,13,14 # 302: 15 # 200: 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31