Created
June 6, 2013 01:16
-
-
Save hoguej/5718646 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
def pieces( count ) | |
indexes = self.piece_indexes( count ) | |
indexes.map{ |index| self[*index] } | |
end | |
def piece_indexes( pieces_count ) | |
chunk_size = self.size / pieces_count | |
chunk_size = 1 if chunk_size < 1 | |
pieces_count = self.size if pieces_count > self.size | |
indexes = [] | |
(0..pieces_count - 1).each do |p| | |
start_index = p * chunk_size | |
indexes << [start_index, chunk_size] | |
end | |
return indexes | |
end | |
end | |
# usage | |
a = [1,2,3,4,5,6,7,8,9,10] | |
a.pieces(2) #[[1,2,3,4,5],[6,7,8,9,10]] | |
a.pieces(5) #[[1,2],[3,4],[5,6],[7,8],[9,10]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@saterus just schooled us all "Just stay in Enumerable"
The
take(count)
at the end I added to remove the extra collections caused by irregular pieces likepieces(3)