How to drop the end of an array in Ruby

arrays, iterator, ruby

Solution

You can also use Array#slice method, e.g.:

[1,2,3,4,5,6].slice(1..4) # => [2, 3, 4, 5]

or

a = [1,2,3,4,5,6]
a.take 3 # => [1, 2, 3]
a.first 3 # => [1, 2, 3]
a.first a.size - 1 # to get rid of the last one

Problem

Array#drop removes the first n elements of an array. What is a good way to remove the last m elements of an array? Alternately, what is a good way to keep the middle elements of an array (greater than n, less than m)?

Original source