Iterate elements in array, except the first two, but also using "each_slice"

Question

Well, I have an array like this:

array = ["month", "value", "january", "30%", "february", "40%"] # etc etc ...

I'm printing the values in pair, I mean:

array.each_slice(2) do |m, v|
    puts "#{m}, #{v}"
end

Outputs:
month, value
january, 30%
february, 40%

Good, but I don't want that outputs: "month, value" (the first two)

I have trying doing this: (found here)

class Array
  def each_after(n)
    each_with_index do |elem, i|
      yield elem if i >= n # Warning : it doesn't work without a block
    end
  end
end

array.each_slice(2).each_after(2) do |m, v|
    puts "#{m}, #{v}"
end

And outputs this error:

<main>: undefined method each_after for ...

I think that the problem is with the "each_after" method, that is made only to use it without the "each_slice".

My question::

How I can modify the "each_after" method to work with the "each_slice" method ?


Show source
| arrays   | ruby   2017-01-03 23:01 1 Answers

Answers to Iterate elements in array, except the first two, but also using &quot;each_slice&quot; ( 1 )

  1. 2017-01-03 23:01

    Your code

    each_slice returns an Enumerable, but you define your method for Array. Just define it for Enumerable :

    module Enumerable
      def each_after(n)
        each_with_index do |elem, i|
          yield elem if i >= n
        end
      end
    end
    

    You can then use

    array.each_slice(2).each_after(1) do |m, v|
        puts "#{m}, #{v}"
    end
    

    Note that you need to drop 1 element (a 2-element Array).

    Without changing your method, you could also use to_a before your Array method :

    array.each_slice(2).to_a.each_after(1) do |m, v|
        puts "#{m}, #{v}"
    end
    

    Alternative

    Just use drop before each_slice :

    ["month", "value", "january", "30%", "february", "40%"].drop(2).each_slice(2).to_a
    #=> [["january", "30%"], ["february", "40%"]]
    

Leave a reply to - Iterate elements in array, except the first two, but also using "each_slice"

◀ Go back