Share This Article
There are a few different ways to remove the first position of an array in Ruby, but the most common is to use the Array#shift method.
This method will remove the first element from an array & return it.
numbers = [5,3,2,1]
numbers.shift
# 5
numbers
# [3,2,1]
If you don’t need the element that was removed, then you can just call the method without assigning it to a variable.
numbers = [5,3,2,1]
numbers.shift
numbers
# [3,2,1]
You can also use the Array#delete_at method to remove an element from an array by its index.
numbers = [5,3,2,1]
numbers.delete_at(0)
# 5
numbers
# [3,2,1]
This method will delete the element at the given index & return the element that was deleted.
You can also use the Array#delete method to delete an element from an array by its value.
This method will delete all occurrences of the given element from the array & return the element that was deleted.
numbers = [5,3,2,1]
numbers.delete(5)
# 5
numbers
# [3,2,1]
If you just want to remove the first occurrence of a given element, then you can use the Array#delete_at method with the Array#index method.
numbers = [5,3,2,1]
numbers.delete_at(numbers.index(5))
# 5
numbers
# [3,2,1]
You can also use the Array#reject! method to remove elements from an array based on a given condition.
This method will remove all elements for which the given block returns true & return the array.
If no elements are deleted, then this method will return nil.
numbers = [5,3,2,1]
numbers.reject! { |num| num == 5 }
# [3,2,1]
numbers = [5,3,2,1]
numbers.reject! { |num| num > 3 }
# [3,2,1]
numbers = [5,3,2,1]
numbers.reject! { |num| num < 3 }
# []
If you want to remove all nil values from an array, then you can use the Array#compact!
or Array#compact
method.
The compact!
method will remove all nil values from the array & return the array.
If no nil values are found, then this method will return nil.
The compact
method will return a new array with all nil values removed.
numbers = [5,3,2,1,nil,nil]
numbers.compact!
# [5,3,2,1]
numbers = [5,3,2,1,nil,nil]
numbers.compact
# [5,3,2,1]
If you want to remove all nil & false values from an array, then you can use the Array#reject
method with a block that returns true for these values.
numbers = [5,3,2,1,nil,false]
numbers.reject { |num| num.nil? || num == false }
# [5,3,2,1]