Skip to content

Instantly share code, notes, and snippets.

@noprompt
Created September 26, 2011 16:13
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 noprompt/1242617 to your computer and use it in GitHub Desktop.
Save noprompt/1242617 to your computer and use it in GitHub Desktop.
Split an array in to n approximately pieces.
# 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