All but last element of Ruby array
Another cool trick
>> *a, b = [1,2,3]
=> [1, 2, 3]
>> a
=> [1, 2]
>> b
=> 3
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
I do it like this:
my_array[0..-2]
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]