Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Created July 19, 2012 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hopsoft/3147080 to your computer and use it in GitHub Desktop.
Save hopsoft/3147080 to your computer and use it in GitHub Desktop.
Divide an Array equally
class Array
# Divides the Array into equally sized chunks.
#
# @example
# list = ["a", "b", "c", "d", "e", "f"]
# list.divide(3) # => [["a", "b"], ["c", "d"], ["e", "f"]]
#
# @param [Integer] count A recommended number of chunks (sub lists) to create.
# The calculated chunk size is rounded up,
# so the number of chunks might be less than what you pass here
# @return [Array<Array>]
def divide(count)
each_slice((length / count.to_f).ceil).to_a
end
end
# A better implementation for this exists in ActiveSupport
# http://rubydoc.info/gems/activesupport/Array#in_groups-instance_method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment