Xavier Noria
4/28/2007 1:46:00 PM
On Apr 28, 2007, at 3:10 PM, Josselin wrote:
> I would like to print n elements from an Array in a cyclic way.
>
> I mean :
>
> using anArray = [ "a", "b", "c", "d", "e", "f", "g"], I should do :
>
> anArray.print_cyclic(4, 0) => "a", "b", "c", "d" (first print 4
> elements starting with the first one)
>
> anArray.print_cyclic_next => "b", "c", "d", "e"
> anArray.print_cyclic_next => "c", "d", "e", "f"
> anArray.print_cyclic_next => "d", "e", "f", "g"
> anArray.print_cyclic_next => "e", "f", "g", "a"
> anArray.print_cyclic_next => "f", "g", "a", "b"
> anArray.print_cyclic_next => "g", "a", "b", "c"
> .....
> also in reverse cycle
> anArray.print_cyclic(4, 0) => "a", "b", "c", "d"
> anArray.print_cyclic_previous => "g", "a", "b", "c"
> anArray.print_cyclic_previous => "f", "g", "a", "b",
>
> what could be the simplest way to do it ? no simple way using
> Array class methods only ,
> should I define a class and methods to loop into the array ? any
> existing lib ? if it has been already done why should I rewrite
> it ....
This is a possible approach:
module Enumerable
def each_cycle(window, start=0)
(start...length+start).each do |i|
yield((i..i+window).map {|n| self[n % length]})
end
end
end
Usage is:
a = [ "a", "b", "c", "d", "e", "f", "g"]
a.each_cycle(4) do |cycle|
puts "#{cycle}"
end
You can delegate reverse cycle to each_cycle on the reverse (and
perhaps taking the opposite of start mod length, depending on the
meaning of start).
-- fxn