Created
September 4, 2019 07:51
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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