On Tuesday, October 22, 2013 at 6:56 PM, Stefan Salewski wrote:
> Hello,
> 
> I would really love to have a cyclic version of each_cons in Ruby --
> I found the version below, which seems to work fine for me. I think that
> method is not too exotic, so it may be good to have this built in.
> 
> https://www.ruby-forum.com/topic/106362
> 
> 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
> 
> Then you can each_cycle anything that is Enumerable, like a Range:
> > > (1..5).each_cycle(3) {|x| p x}
> > 
> 
> [1, 2, 3]
> [2, 3, 4]
> [3, 4, 5]
> [4, 5, 1]
> [5, 1, 2]
> => 1..5
> > > { 'dog' => 'Rover', 'cat' => 'Mittens', 'fish' =>
> > 
> 
> 'Goldie' }.each_cycle(2) {|x| p x}
> [["cat", "Mittens"], ["fish", "Goldie"]]
> [["fish", "Goldie"], ["dog", "Rover"]]
> [["dog", "Rover"], ["cat", "Mittens"]]
> => {"cat"=>"Mittens", "fish"=>"Goldie", "dog"=>"Rover"}


Why not:

> (1..5).cycle.each_cons(3).take(5).each { |x| p x }
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 1]
[5, 1, 2]



?
:-)