开发者

Simple question about deleting an object from a Ruby array

开发者 https://www.devze.com 2023-01-25 13:30 出处:网络
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

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, ob开发者_运维问答ject3]

Thanks for reading.


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

No spots here...


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

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

>> arr.slice!(1)
object2

>> arr
[object1, object3]
0

精彩评论

暂无评论...
验证码 换一张
取 消