简体   繁体   中英

How can I delete an element from an array using its index?

Trying to delete from this array:

array = ["Dog", "Cat", "John Cena"]

But those won't work:

array.delete(1)
array.delete([1])

Any help is appreciated.

It's delete_at you needed:

array = ["Dog", "Cat", "John Cena"]
#=> ["Dog", "Cat", "John Cena"]
array.delete_at(1)
#=> "Cat"
array
#=> ["Dog", "John Cena"]

Please check the doc more often, you'll probably find the thing you needed most of the times.

Alternatively:

array = ["Dog", "Cat", "John Cena"]
array[1, 1] = []
array # => ["Dog", "John Cena"]

As stated before you should be using Ruby Docs for help like this Ruby has amazing documentation and is a shame to waste the wealth of knowledge here.

https://ruby-doc.org/core-2.1.0/Array.html#method-i-delete_at

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM