在数组中迭代元素,除了前两个,还使用“each_slice”

时间:2021-05-31 21:34:49

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".

我认为问题在于“each_after”方法,即只在没有“each_slice”的情况下使用它。

My question::

我的问题::

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

如何修改“each_after”方法以使用“each_slice”方法?

1 个解决方案

#1


4  

Your code

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

each_slice返回一个可枚举的,但是您定义了数组的方法。定义为可枚举:

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).

注意,您需要删除一个元素(一个2元素数组)。

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

在不改变方法的情况下,也可以在数组方法之前使用to_a:

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

Alternative

Just use drop before each_slice :

在每个切片之前使用drop:

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

#1


4  

Your code

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

each_slice返回一个可枚举的,但是您定义了数组的方法。定义为可枚举:

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).

注意,您需要删除一个元素(一个2元素数组)。

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

在不改变方法的情况下,也可以在数组方法之前使用to_a:

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

Alternative

Just use drop before each_slice :

在每个切片之前使用drop:

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