Skip to content

Instantly share code, notes, and snippets.

@mvoto
Forked from klebervirgilio/gist:2161451
Created March 22, 2012 18:50
Show Gist options
  • Save mvoto/2161722 to your computer and use it in GitHub Desktop.
Save mvoto/2161722 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]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment