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 1:
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]
Solution 2:
Out of curiosity, why don't you like a[0...-1]
? You want to get a slice of the array, so the slice operator seems like the idiomatic choice.
But if you need to call this all over the place, you always have the option of adding a method with a more friendly name to the Array class, like DigitalRoss suggested. Perhaps like this:
class Array
def drop_last
self[0...-1]
end
end
Solution 3:
Another cool trick
>> *a, b = [1,2,3]
=> [1, 2, 3]
>> a
=> [1, 2]
>> b
=> 3
Solution 4:
If you want to perform a pop()
operation on an array (which is going to result in the last item deleted), but you're interested in obtaining the array instead of a popped element, you can use tap(&:pop)
:
> arr = [1, 2, 3, 4, 5]
> arr.pop
=> 5
> arr
=> [1, 2, 3, 4]
> arr.tap(&:pop)
=> [1, 2, 3]
Solution 5:
I do it like this:
my_array[0..-2]