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

3
  • 1
    when you call 1 do u want to remove specific number or first number of array ? Commented Apr 14, 2016 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. Commented Apr 14, 2016 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] Commented Apr 14, 2016 at 23:05

3 Answers 3

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] 
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking about perf of delete_at Vs. slice! ... they should be ~ the same.
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)

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.