Skip to content

Instantly share code, notes, and snippets.

@SteveBenner
Last active December 17, 2015 21:39
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 SteveBenner/5676588 to your computer and use it in GitHub Desktop.
Save SteveBenner/5676588 to your computer and use it in GitHub Desktop.
Subdivide a list into sub-lists of specified length
# @param [Array<Integer>] List of sizes of the partitions self will be subdivided into
# @return [Object] Array containing self divided into one or more sub-arrays of size n
# @example
# [1,2,3].subdv [1] #=> [[1]]
# [1,2,3].subdv [3] #=> [[1,2,3]]
# [1,2,3].subdv [1,2] #=> [[1],[2,3]]
# [1,2,3].subdv [1,2] #=> [[1],[2,3]]
# [1,2,3].subdv [1,1,1] #=> [[1],[2],[3]]
# [1,2,3].subdv [1,2,1] #=> [[1],[2,3],[]]
def subdv(arr)
arr.reduce([]) { |ret, n| ret << self.slice!(0..n-1) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment