I want to remove (only one) element by value from my array.
example :
x = [1,2,3,2]
x.remove(2)
result: x= [1,3]
But, i want to get [1,3,2]
.
thanks
I want to remove (only one) element by value from my array.
example :
x = [1,2,3,2]
x.remove(2)
result: x= [1,3]
But, i want to get [1,3,2]
.
thanks
As @7urkm3n mentioned in the comments, you can use x.delete_at
to delete the first occurance
x.delete_at(x.index 2)
> x = [1,2,3,2]
=> [1, 2, 3, 2]
> x.delete_at(x.index 2)
=> 2
> x
=> [1, 3, 2]
You can use slice!(index, 1)
. You can get the 1st index of the element you want to delete by using index(element)
In your case you just have to do: x.slice!(x.index(2), 1)
(or, as already mentioned, delete_at
just providing the index)
You could write
x = [1,2,3,2]
x.difference([2])
#=> [1, 3, 2]
where Array#difference
is as I've defined it my answer here. Because of the wide potential application of the method I've proposed it be added to the Ruby core.
Suppose
x = [1,2,3,2,1,2,4,2]
and you wished to remove the first 1
, the first two 2
's and the 4
. To do that you would write
x.difference([1,2,2,4])
#=> [3, 1, 2, 2]
Note that
x.difference([1,2,2,4,4,5])
#=> [3, 1, 2, 2]
gives the same result.
To remove the last 1
, the last two 2
s and and the 4
, write
x.reverse.difference([1,2,2,4]).reverse
#=> [1, 2, 3, 2]