3

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

ayoubben
  • 35
  • 1
  • 2
  • 10
  • 1
    when you call `1` do u want to remove specific number or first number of array ? – 7urkm3n Apr 14 '16 at 22:57
  • 1
    you can use `.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 call `x.uniq`. – 7urkm3n Apr 14 '16 at 23:00
  • i do not want to keep uniq array, i just need to delete the number that the customer enter, if i have x = [1,1,1], i want to keep [1,1] – ayoubben Apr 14 '16 at 23:05

3 Answers3

8

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] 
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

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)

stecb
  • 14,478
  • 2
  • 50
  • 68
0

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]
Community
  • 1
  • 1
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100