Search code examples
ruby

All but last element of Ruby array


Let's say I have a Ruby array

a = [1, 2, 3, 4]

If I want all but the first item, I can write a.drop(1), which is great. If I want all but the last item, though, I can only think of this way

a[0..-2]   # or
a[0...-1]

but neither of these seem as clean as using drop. Any other built-in ways I'm missing?


Solution

  • Perhaps...

    a = t               # => [1, 2, 3, 4]
    a.first a.size - 1  # => [1, 2, 3]
    

    or

    a.take 3
    

    or

    a.first 3
    

    or

    a.pop
    

    which will return the last and leave the array with everything before it

    or make the computer work for its dinner:

    a.reverse.drop(1).reverse
    

    or

    class Array
      def clip n=1
        take size - n
      end
    end
    a          # => [1, 2, 3, 4]
    a.clip     # => [1, 2, 3]
    a = a + a  # => [1, 2, 3, 4, 1, 2, 3, 4]
    a.clip 2   # => [1, 2, 3, 4, 1, 2]