Ruby Tuesday – Array#drop

Today’s Ruby Tuesday continues with looking at the Array class type as a queue, and covers Array#drop.

While Ruby does not have a tail function on Array, you can emulate that functionality by calling Array#drop and passing a 1 as the argument to the method.

Array#drop takes a non-negative integer, “N”, as it’s argument and returns the an array of elements with the first N-elements removed.

[1, 2, 3, 4, 5].drop 1
# => [2, 3, 4, 5]
[1, 2, 3, 4, 5].drop 3
# => [4, 5]
[1, 2, 3, 4, 5].drop 0
# => [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5].drop -1
# ArgumentError: attempt to drop negative size
# from (pry):9:in `drop'

If we call Array#drop on an empty array, we get back an empty array as well.

[].drop 1
# => []

And unlike other methods on Array, like Array#pop from last time, which mutate the underlying value (and don’t end with a !) we can see that calling Array#drop does not modify the original array object.

my_queue = [1, 2, 3, 4, 5]
# => [1, 2, 3, 4, 5]
my_queue.drop 1
# => [2, 3, 4, 5]
my_queue
# => [1, 2, 3, 4, 5]

Trying it out, we also see that there is not a destructive version of the drop method, as we get a NoMethodError when we try it.

my_queue.drop! 1
# NoMethodError: undefined method `drop!' for [1, 2, 3, 4, 5]:Array
# from (pry):13:in `__pry__'

–Proctor