Ruby. Iterating through a collection within specified a window

Rust has a method - windows (or equivalent - chunks)

  fn main() {
    let ints = [0, 1, 2, 3, 4, 5, 6, 7, 8];
    let slice = &ints;

    for el in slice.windows(3) {
      println!("window {:?}", el)
    }
  }
that allows you to iterate through a slice and read elements within specified a window. Below is the implementation of similar functionality in Ruby:

module Enumerable
  def windows(n)
    raise ArgumentError.new("Expected a value greater than 0") if n <= 0

    return to_enum(:windows, n) unless block_given?
    return nil if self.size == 0

    (0..(self.size/n)).each do |i|
      l = i * n
      yield self[l...(l + n)]
    end
  end
  
  alias_method :chunks, :windows
end

irb(main):014:0> [0, 1, 2, 3, 4, 5, 6, 7, 8].windows(3).each { |el| puts el.join(',') }
0,1,2
3,4,5
6,7,8

irb(main):015:0> [0, 1, 2, 3, 4, 5, 6, 7, 8].windows(0).each { |el| puts el.join(',') }
(irb):3:in `windows': Expected a value greater than 0 (ArgumentError)

irb(main):016:0> windows = [0, 1, 2, 3, 4, 5, 6, 7, 8].windows(5)
=> #
irb(main):017:0> windows.each { |el| puts el.join(',') }
0,1,2,3,4
5,6,7,8

No comments :

Post a Comment