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 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 2s and and the 4, write
x.reverse.difference([1,2,2,4]).reverse
#=> [1, 2, 3, 2]
1do u want to remove specific number or first number of array ?.delete_at(index of array)for that, or u can keep uniq like from[1,2,3,4,1]to make to make it[1,2,3,4]. just callx.uniq.