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?<
Compiling all the different options for delete in ruby
delete - Deletes matching elements by value. If more than one value matches it will remove all. If you don't care about the number of occurrence or sure about single occurrence, use this method.
a = [2, 6, 3, 5, 3, 7]
a.delete(3) # returns 3
puts a # return [2, 6, 5, 7]
delete_at - Deletes element at given index. If you know the index use this method.
# continuing from the above example
a.delete_at(2) # returns 5
puts a # returns [2, 6, 7]
delete_if - Deletes every element for which block is true. This will modify the array. Array changes instantly as the block is called.
b = [1, 2, 5, 4, 9, 10, 11]
b.delete_if {|n| n >= 10}. # returns [1, 2, 5, 4, 9]
reject - This will return new array with the elements for which the given block is false. The ordering is maintained with this.
c = [1, 2, 5, 4, 9, 10, 11]
c.reject {|n| n >= 10}. # returns [1, 2, 5, 4, 9]
reject! - same as delete_if. Array may not change instantly as the block is called.
If you want to delete multiple values from array, the best option is as bellow.
a = [2, 3, 7, 4, 6, 21, 13]
b = [7, 21]
a = a - b # a - [2, 3, 4, 6, 13]