Created
July 19, 2012 21:48
-
-
Save hopsoft/3147080 to your computer and use it in GitHub Desktop.
Divide an Array equally
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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