Skip to content

Instantly share code, notes, and snippets.

@RyanScottLewis
Created September 4, 2019 07:51
Show Gist options
  • Save RyanScottLewis/f21cd7eaee5b24d25c3fe83c61a8cd62 to your computer and use it in GitHub Desktop.
Save RyanScottLewis/f21cd7eaee5b24d25c3fe83c61a8cd62 to your computer and use it in GitHub Desktop.

Revisions

  1. RyanScottLewis created this gist Sep 4, 2019.
    44 changes: 44 additions & 0 deletions cycling_slicer.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    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