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.rb161 chars6 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.rb173 chars6 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"]
.
gistlibby LogSnag