Skip to content

Instantly share code, notes, and snippets.

@RyanScottLewis
Created September 4, 2019 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanScottLewis/f21cd7eaee5b24d25c3fe83c61a8cd62 to your computer and use it in GitHub Desktop.
Save RyanScottLewis/f21cd7eaee5b24d25c3fe83c61a8cd62 to your computer and use it in GitHub Desktop.
Extend Ruby Enumerable with `#each_cycling_slice`, which cycles though the given list of slice sizes/widths.
class CyclingSlicer
def initialize(slices)
@slices = slices.cycle
@slice = @slices.next
@counter = 0
end
def slice?
@counter += 1
return false unless @counter % @slice == 0
@slice = @slices.next
@counter = 0
true
end
end
module Enumerable
# Slice with a cycling list of slice widths.
#
# @example
# (1..12).each_cycling_slice(1, 2, 3) do |slice|
# p slice
# end
# # => [1]
# # => [2, 3]
# # => [4, 5, 6]
# # => [7]
# # => [8, 9]
# # => [10, 11, 12]
def each_cycling_slice(*slices, &block)
slices = [1] if slices.empty?
slicer = CyclingSlicer.new(slices)
slice_after { slicer.slice? }.each(&block)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment