例如a = [1,2,3,1]
如果您使用 a.delete 1
,结果是 a = [2,3]
有没有一种方法可以从有限制的数组中删除?伪代码:
a = [1,2,3,4,1]
a.delete(1, *limit 1*)
#=> [2,3,4,1]
最佳答案
我能想到的一个想法是——
n.times { array.delete_at array.index(item) }
delete_at
- 删除指定索引处的元素,返回该元素,如果索引超出范围,则返回 nil。
index
- 返回 ary 中第一个对象的索引,使得该对象 == 到 obj。
您可以将逻辑包装在一个方法中,如下所示:-
def delete_with_limit(array, item, limit)
count = array.count(item)
raise "only #{count} is present, and you are expecting #{limit}" if limit > count
limit.times { array.delete_at array.index(item) }
array
end
array = [1,2,1,1,3,5]
delete_with_limit(array, 1, 2) # => [2, 1, 3, 5]
array = [1,2,1,1,3,5]
delete_with_limit(array, 1, 4)
# `delete_with_limit': only 3 is present, and you are expecting 4 (RuntimeError)
关于ruby - 有没有一种方法可以只删除 1 个匹配的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24051220/