选择除阵列中的当前所有内容

use*_*294 2 ruby arrays iteration

a = [1,4,1]
total = []

a.each do |num|
  total << a.select {|x| x != num}
end

p total => [[4], [1, 1], [4]]
Run Code Online (Sandbox Code Playgroud)

我希望选择除当前元素之外的数组中的所有其他元素.当没有重复时,上述工作正常,但是当存在时,输出不正确.在这种情况下,输出应为:

[[4,1], [1, 1], [1,4]]
Run Code Online (Sandbox Code Playgroud)

我尝试使用each_with_index并定位索引而不是数字,但遇到了同样的问题.有任何想法吗?选择以外的东西?

谢谢

use*_*559 5

我不是一个Ruby开发人员,所以如果这不是惯用语,请道歉,但请试一试?

a = [1,4,1]

total = a.each_index.map { |index| a[0...index] + a[(index+1)..-1] }

p total
Run Code Online (Sandbox Code Playgroud)

  • 这是一个智能解决方案.@ user3007294也看看`Array#combination`.例如`a.combination(a.size - 1).to_a#=> [[4,1],[1,1],[1,4]]`(虽然订单无法保证) (3认同)