删除数组元素相匹配的第一个实例 [英] Delete first instance of matching element from array
本文介绍了删除数组元素相匹配的第一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有数组 [1,2,3,1,2,3]
,我想删除(说)<$ C $的第一个实例C> 2 从数组给 [1,3,1,2,3]
。什么是最简单的方法?
解决方案
li.delete_at(li.index(N)|| li.length)
李[li.length]
超出范围,因此 || li.length
处理,其中 N
不在列表中的情况。
IRB(主):001:0&GT;李= [1,2,3,1,2,3]
= GT; [1,2,3,1,2,3]
IRB(主):002:0&GT; li.delete_at(li.index(2)|| li.length)
= GT; 2
IRB(主):003:0&GT; li.delete_at(li.index(42)|| li.length)
= GT;零
IRB(主):004:0&GT;里
= GT; [1,3,1,2,3]
Say I have the array [1,2,3,1,2,3]
and I want to delete the first instance of (say) 2
from the array giving [1,3,1,2,3]
. What's the easiest way?
解决方案
li.delete_at(li.index(n) || li.length)
li[li.length]
is out of range, so the || li.length
handles the case where n
isn't in the list.
irb(main):001:0> li = [1,2,3,1,2,3]
=> [1, 2, 3, 1, 2, 3]
irb(main):002:0> li.delete_at(li.index(2) || li.length)
=> 2
irb(main):003:0> li.delete_at(li.index(42) || li.length)
=> nil
irb(main):004:0> li
=> [1, 3, 1, 2, 3]
这篇关于删除数组元素相匹配的第一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文