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?
You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove. The splice method can accept many arguments.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array.
You can use the pop() method to remove an element from the array.
I think I've figured it out:
a = [3, 2, 4, 6, 3, 8] a.delete(3) #=> 3 a #=> [2, 4, 6, 8]
Borrowing from Travis in the comments, this is a better answer:
I personally like
[1, 2, 7, 4, 5] - [7]
which results in=> [1, 2, 4, 5]
fromirb
I modified his answer seeing that 3 was the third element in his example array. This could lead to some confusion for those who don't realize that 3 is in position 2 in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With