Created
September 26, 2011 16:13
-
-
Save noprompt/1242617 to your computer and use it in GitHub Desktop.
Split an array in to n approximately pieces.
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
# Split an array in to n approximately equal pieces. | |
# | |
# Example usage: | |
# | |
# ('a'..'f').to_a.split_in_to(3) => [["a", "b"], ["c", "d"], ["e", "f"]] | |
# (1..7).to_a.split_in_to(2) => [[1, 2, 3, 4], [5, 6, 7]] | |
class Array | |
def split_into(pieces = 2) | |
len = self.count | |
f = (len.to_f / pieces).ceil | |
1.upto(pieces).reduce([]) {|xs, i| xs << self[f*(i - 1)..(f*i - 1)] } | |
end | |
end | |
# Stand alone version | |
def split_into(array, pieces = 2) | |
len = array.count | |
f = (len.to_f / pieces).ceil | |
1.upto(pieces).reduce([]) {|xs, i| xs << array[f*(i - 1)..(f*i - 1)] } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment