Array.insert / delete / delete_at / compact
Methods for inserting and removing elements at arbitrary positions in an array, and for removing nil values.
Syntax
# Inserts one or more elements at the specified index.
array.insert(index, element, ...)
# Removes all elements matching the specified value.
array.delete(value)
array.delete(value) { return_value_if_not_found }
# Removes the element at the specified index.
array.delete_at(index)
# Returns a new array with nil elements removed.
array.compact
# Removes nil elements in place (destructive).
array.compact!
Method List
| Method | Description |
|---|---|
| insert(idx, elem, ...) | Inserts one or more elements at the specified index. A negative index counts from the end of the array. |
| delete(val) | Removes all elements equal to the specified value and returns that value. Returns nil if no match is found. |
| delete_at(idx) | Removes the element at the specified index and returns it. |
| compact | Returns a new array with all nil elements removed. The original array is not modified. |
| compact! | Removes nil elements from the array in place. Returns the array if any changes were made, or nil if there was nothing to remove. |
Sample Code
colors = ["red", "blue", "yellow"]
# Insert "green" at index 1 using insert.
colors.insert(1, "green")
puts colors.inspect # ["red", "green", "blue", "yellow"]
# Multiple elements can be inserted at once.
colors.insert(2, "purple", "orange")
puts colors.inspect # ["red", "green", "purple", "orange", "blue", "yellow"]
# Remove a value using delete.
colors.delete("orange")
puts colors.inspect # ["red", "green", "purple", "blue", "yellow"]
# Use a block to specify a default return value when the element is not found.
result = colors.delete("white") { "not found" }
puts result # not found
# Remove by index using delete_at.
removed = colors.delete_at(0)
puts removed # red
puts colors.inspect # ["green", "purple", "blue", "yellow"]
# Remove nil values using compact.
data = [1, nil, 2, nil, 3, nil]
puts data.compact.inspect # [1, 2, 3]
puts data.inspect # [1, nil, 2, nil, 3, nil] (original unchanged)
# Modify the array in place using compact!.
data.compact!
puts data.inspect # [1, 2, 3]
Notes
Use insert to add elements in the middle of an array. For appending to the end, push or << is faster. Use delete to remove elements by value, and delete_at to remove an element by index.
delete removes all elements that match the given value, so if the same value appears multiple times, every occurrence will be deleted. Use delete_at when you need to remove only the element at a specific position.
Use compact to clean up unwanted nil values that appear as a result of array processing. To remove duplicate elements, use uniq. For operations at the end or beginning of an array, use push / pop / shift / unshift.
If you find any errors or copyright issues, please contact us.