据我所知,当我删除 Array.The 中的一个元素时,索引仍然向前移动。当我删除循环中的元素时,如何使索引静止?
下面只是一个例子。在这个例子中,我希望删除所有具有唯一 num 的元素,但最后仍然留下了 num '2' 。
class Test
attr_accessor :num
attr_accessor :job
def initialize(num,job)
@num = num
@job = job
end
end
a = []
a << Test.new(1,'jobA')
a << Test.new(2,'jobB')
a << Test.new(1,'jobC')
a << Test.new(3,'jobD')
b = Hash.new
a.each_with_index do |i,index|
#puts i.num,index
if b[i.num] == nil
b[i.num] = true
a.delete(i)
end
end
a.each do |i|
puts i.num,i.job
end
# it shows:
# 2 jobB
# 1 jobC
# I hope to get only:
# 1 jobC
在这个新示例中,我希望留下重复的 num '1' 的 'jobC',并希望删除其他唯一的 num 元素。
希望有人能帮忙,谢谢!
我最终使用 delete_if ,感谢您的所有回复对我的帮助。