How can I delete one element from an array by value

前端 未结 15 996
独厮守ぢ
独厮守ぢ 2020-12-04 05:16

I have an array of elements in Ruby

[2,4,6,3,8]

I need to remove elements with value 3 for example

How do I do that?<

相关标签:
15条回答
  • 2020-12-04 05:52

    Non-destructive removal of first occurrence:

    a = [2, 4, 6, 3, 8]
    n = a.index 3
    a.take(n)+a.drop(n+1)
    
    0 讨论(0)
  • 2020-12-04 05:54

    I'm not sure if anyone has stated this, but Array.delete() and -= value will delete every instance of the value passed to it within the Array. In order to delete the first instance of the particular element you could do something like

    arr = [1,3,2,44,5]
    arr.delete_at(arr.index(44))
    
    #=> [1,3,2,5]
    

    There could be a simpler way. I'm not saying this is best practice, but it is something that should be recognized.

    0 讨论(0)
  • 2020-12-04 05:56

    You can also monkey patch it. I never understood why Ruby has an except method for Hash but not for Array:

    class Array
      def except value
        value = value.kind_of(Array) ? value : [value]
        self - value
      end
    end
    

    Now you can do:

    [1,3,7,"436",354,nil].except(354) #=> [1,3,7,"436",nil]
    

    Or:

    [1,3,7,"436",354,nil].except([354, 1]) #=> [3,7,"436",nil]
    
    0 讨论(0)
  • 2020-12-04 05:58

    So when you have multiple occurrences of 3 and you want only to delete the first occurrence of 3, you can simply do some thing as below.

    arr = [2, 4, 6, 3, 8, 10, 3, 12]
    
    arr.delete_at arr.index 3
    
    #This will modify arr as [2, 4, 6, 8, 10, 3, 12] where first occurrence of 3 is deleted. Returns the element deleted. In this case => 3.
    
    0 讨论(0)
  • 2020-12-04 05:59

    You can simply run:

    [2,4,6,3,8].delete(3)
    
    0 讨论(0)
  • 2020-12-04 06:00

    Assuming you want to delete 3 by value at multiple places in an array, I think the ruby way to do this task would be to use the delete_if method:

    [2,4,6,3,8,3].delete_if {|x| x == 3 } 
    

    You can also use delete_if in removing elements in the scenario of 'array of arrays'.

    Hope this resolves your query

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