remove an element from an array at a specific index in ruby

You can use the delete_at method to remove an element from a specific index of an array in Ruby. Here's an example:

main.rb
fruits = ["apple", "banana", "orange", "grape"]
index_to_remove = 2
fruits.delete_at(index_to_remove)
puts fruits.inspect
# Output: ["apple", "banana", "grape"]
161 chars
6 lines

In this example, fruits.delete_at(index_to_remove) removes the element at index 2, which is "orange". The resulting array is ["apple", "banana", "grape"].

Note that delete_at modifies the original array and returns the deleted element. If you just want to get the updated array, you can use slice! instead:

main.rb
fruits = ["apple", "banana", "orange", "grape"]
index_to_remove = 2
removed_item = fruits.slice!(index_to_remove)
puts fruits.inspect
# Output: ["apple", "banana", "grape"]
173 chars
6 lines

In this example, fruits.slice!(index_to_remove) removes the element at index 2, which is "orange", and returns it as the removed_item variable. The resulting array is ["apple", "banana", "grape"].

related categories

gistlibby LogSnag