Delete first instance of matching element from array

后端 未结 3 1849
有刺的猬
有刺的猬 2020-12-03 02:58

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 e

相关标签:
3条回答
  • 2020-12-03 03:21
    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]
    
    0 讨论(0)
  • 2020-12-03 03:25

    Maybe it should become part of stdlib:

    class Array
      def delete_first item
        delete_at(index(item) || length)
      end
    end
    
    0 讨论(0)
  • 2020-12-03 03:29

    If || li.length is to avoid sending nil to li.delete_at (which would result in a TypeError), then a more readable version might look like this

    li.delete_at li.index(42) unless li.index(42).nil?

    0 讨论(0)
提交回复
热议问题