Skip to content

Instantly share code, notes, and snippets.

@hoguej
Created June 6, 2013 01:16
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 hoguej/5718646 to your computer and use it in GitHub Desktop.
Save hoguej/5718646 to your computer and use it in GitHub Desktop.
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]]
@bostonaholic
Copy link

@saterus just schooled us all "Just stay in Enumerable"

def pieces(count)
  self.each_slice(self.count / count).take(count)
end

The take(count) at the end I added to remove the extra collections caused by irregular pieces like pieces(3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment