![](/img/trans.png)
[英]ERB: iterate over an array and output each value as part of a one line string
[英]Iterate array and leave one out in each step
如何在Ruby中迭代數組的元素,並且在每一步中,我都可以對包含所有元素的數組做一些事情,但此刻要迭代的元素除外?
例如對於[4,2,8]
我迭代元素,然后我可以用
[2,8]
[4,8]
[4,2]
這實際上不是直接可能的 (除非您不需要缺少的元素)。 但是您可以自己編程:
選項1-這樣做 :
a = [11,22,33,44,55]
a.each_with_index { |e,i|
p e
p a.take(i) + a[i+1..-1]
}
選項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
}
任何一個的輸出:
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])
}}
要么
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)}
確實看起來像您想要Array#combination
:
[4,2,8].combination(2).each do |ary|
p ary
end
哪個輸出:
[4, 2]
[4, 8]
[2, 8]
創建的每個子數組都屈服於該塊,在本例中為ary
,因此您可以使用值進行所需的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.