从数组中删除匹配元素的第一个实例 [英] Delete first instance of matching element from array
本文介绍了从数组中删除匹配元素的第一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有数组 [1,2,3,1,2,3]
并且我想从数组给出 [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]
超出范围,所以 ||li.length
处理 n
不在列表中的情况.
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屋!
查看全文