简体   繁体   English

迭代数组,并在每个步骤中省略一个

[英]Iterate array and leave one out in each step

How do I iterate the elements of an array in Ruby and in each step I can do something with the array containing all elements, except the one that is iterated in the moment? 如何在Ruby中迭代数组的元素,并且在每一步中,我都可以对包含所有元素的数组做一些事情,但此刻要迭代的元素除外?

For instance for [4,2,8] I iterate the elements and then I can do something with 例如对于[4,2,8]我迭代元素,然后我可以用

  • [2,8]
  • [4,8]
  • [4,2]

It's not really directly possible (unless you do not need the missing element). 这实际上不是直接可能的 (除非您不需要缺少的元素)。 But you can program it yourself: 但是您可以自己编程:

Option 1 - just do it : 选项1-这样做

a = [11,22,33,44,55]

a.each_with_index { |e,i|
  p e
  p a.take(i) + a[i+1..-1]
}

Option 2 - integrate with Array : 选项2-与Array集成

class Array
  def each_excluded(&block)
    self.each_with_index { |e, i|
      yield(e, self.take(i) + self[i+1..-1])
    }
  end
end

a.each_excluded { |e, rest|
  p e
  p rest
}

Output from either one: 任何一个的输出:

11
[22, 33, 44, 55]
22
[11, 33, 44, 55]
33
[11, 22, 44, 55]
44
[11, 22, 33, 55]
55
[11, 22, 33, 44]

您可以使用slice方法并使用包含索引的项目创建一个新数组。

[4, 2, 8].tap{|a| a.length.times{|i| 
  do_something_you_want_with(a[0...i]+a[i+1..-1])
}}

or 要么

class Array
  def each_but_one &pr
    length.times{|i| pr.call(self[0...i]+self[i+1..-1])}
  end
end

[4, 2, 8].each_but_one{|a| do_something_you_want_with(a)}

It really looks like you want Array#combination : 确实看起来像您想要Array#combination

[4,2,8].combination(2).each do |ary|
  p ary
end

Which outputs: 哪个输出:

[4, 2]
[4, 8]
[2, 8]

Each sub-array created is yielded to the block, in this case to ary , so you can do what you want with the values. 创建的每个子数组都屈服于该块,在本例中为ary ,因此您可以使用值进行所需的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM