在Ruby中,有没有办法轻松删除数组中的1个匹配?

nop*_*ole 19 ruby

在Ruby中,数组减法或 reject

>> [1,3,5,7,7] - [7]
=> [1, 3, 5]

>> [1,3,5,7,7].reject{|i| i == 7}
=> [1, 3, 5]
Run Code Online (Sandbox Code Playgroud)

将删除数组中的所有条目.是否容易删除1次?

mbm*_*mbm 26

>> a = [1,3,5,7,7]

>> a.slice!(a.index(7))
=> 7

>> a
=> [1,3,5,7]
Run Code Online (Sandbox Code Playgroud)

  • 有人可能想检查'7'是否确实存在,否则可能引发类型错误. (2认同)

sep*_*p2k 13

我能想到的最好的是:

found = false
[1,3,5,7,7].reject{|i| found = true if !found && i == 7}
Run Code Online (Sandbox Code Playgroud)

或破坏性地:

arr = [1, 2, 3, 5, 7, 7]
arr.delete_at( arr.index(7))
arr #=> [1, 2, 3, 5, 7]
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,在第二种解决方案中,您可能还需要添加 `if pos`,因为 `delete_at(nil)` 会抛出异常。 (2认同)