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?
For instance for [4,2,8]
I iterate the elements and then I can do something with
[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 :
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 :
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
:
[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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.