如何在Ruby中和每個步驟中迭代數組的元素我可以對包含所有元素的數組執行某些操作,但當前迭代的元素除外?迭代數組並在每個步驟中留下一個
例如,對於[4,2,8]
我重複的元素,然後我可以做一些與
[2,8]
[4,8]
[4,2]
如何在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 method並創建一個新的數組除了索引號之外的項目。
[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
,所以你可以做你想要的值。
'從ary中刪除前n個元素並返回數組中的其餘元素.'我只想刪除一個元素。 –
請參閱編輯 - 切片方法(我必須誤讀文檔)。 –