What is array.drop() in Ruby?

The array.drop() method in Ruby removes the first n numbers of elements in an array.

array.drop() returns an array that contains the remaining elements. If the n number of elements passed to this method is negative, an error will be thrown.

Unlike other methods that permanently change or alter the original array, the drop() method leaves the original array as it was before the function call.

Syntax


array.drop(n)

Parameters

  • n: The first n number of elements you want to remove from the array.

Return value

The return value is a new array that contains the remaining elements that were not removed.

# create arrays
arr1 = [1, 2, 3, 4, 5]
arr2 = ["a", "b", "c", "d", "e"]
arr3 = ["Ruby", "Java", "JavaScript", "Python"]
arr4 = ["1ab", "2cd", "3ef", "4gh", "5ij"]
arr5 = [nil, "nil", "true", "false", true]
# drop some elements
a = arr1.drop(2)
b = arr2.drop(4)
c = arr3.drop(0)
d = arr4.drop(2)
e = arr5.drop(2)
# print out returned values
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"
puts "#{e}"
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources