Skip to content

Instantly share code, notes, and snippets.

@klebervirgilio
Created March 22, 2012 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save klebervirgilio/2161451 to your computer and use it in GitHub Desktop.
Save klebervirgilio/2161451 to your computer and use it in GitHub Desktop.
Array#by
class Array
def by(n)
buff, self_ = [], self.clone
if self.size % n == 0
(self.size/n).times{ buff << self_.shift(n) }
end
buff
end
end
# by @mvoto
class Array
def by(n)
self.enum_for(:each_slice, n).to_a
end
end
[1,2,3,4,5,6].by(2) #=> [[1, 2], [3, 4], [5, 6]]
#:P
[*0...9].each_slice(3).to_a => [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment