Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.drop() in Ruby?

okwudili onyejiaku

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}"

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring