ruby - 有没有一种方法可以只删除 1 个匹配的数组元素?

标签 ruby arrays

例如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/

相关文章:

ruby - 在 Module#included 中的 class_eval 中定义类变量

ruby-on-rails - rails 的 activerecord 将数据存储到错误的表中

c# - Array.Exist() 只识别数组的最后一个元素

javascript - React/Redux 我可以使用reverse()

ruby-on-rails - ActiveRecord 关系的排序问题

arrays - 按数字过滤 Matlab 元胞数组会留下虚假错误

ruby - 在 Ruby 中提取 URI 最后一段的最佳方法

ruby-on-rails - rails 4 : Render partial in div after submit button click

c# - 在 C# 中打印数组/列表到 Excel

ruby - 使用 ruby​​zip 时权限被拒绝