0

I have a Ruby (1.9.2) array which I need to remove an object from.

[object1, object2, object3]

At the moment I'm doing

array.delete_at(1)

which removes the object, but then there is an empty array spot at that index.

[object1, , object3]

How do I remove an object so that the array is resized so that there is no empty spot in the array?

[object1, object3]

Thanks for reading.

2
  • For future reference, if you have an array with nil elements, you can use Array.compact to strip them out. Commented Nov 18, 2010 at 17:36
  • Not sure why your question got downvoted, but I did a +1 to it because it's a valid question. Commented Nov 18, 2010 at 17:38

2 Answers 2

4
irb> a = [1,2,3]
=> [1, 2, 3]
irb> a.delete_at 1
=> 2
irb> a
=> [1, 3]

No spots here...

Sign up to request clarification or add additional context in comments.

1 Comment

Confirmed, with 1.8.7, 1.9.1, and 1.9.2
0

I think slice! is the method you're looking for

>> arr = [object1, object2, object3]
[object1, object2, object3]

>> arr.slice!(1)
object2

>> arr
[object1, object3]

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.