Skip to content

Instantly share code, notes, and snippets.

@dmichael
Created June 16, 2009 23:19
Show Gist options
  • Select an option

  • Save dmichael/130975 to your computer and use it in GitHub Desktop.

Select an option

Save dmichael/130975 to your computer and use it in GitHub Desktop.
# http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/249436
class Array
def each_cycle(window, start=0)
(start...length+start).each do |i|
yield((i..i+window).map {|n| self[n % length]})
end
end
end
# Something a little more complicated from
# http://talklikeaduck.denhaven2.com/2007/04/30/our-kind-of-ducks-odd-ducks-and-trained-ducks
module Enumerable
def each_cycle(window, start=0)
wrap_start = []
cache = []
each_with_index do |e,i|
cache << e
if i >= start + (window - 1)
yield cache[start, window]
cache.shift
else
wrap_start << e
end
end
wrap_start.each do |e|
cache << e
yield cache[start, window]
cache.shift
end
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment