Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All but last element of Ruby array

Tags:

ruby

People also ask

How can you get the last item of an array Ruby?

Ruby | Array class last() function last() is a Array class method which returns the last element of the array or the last 'n' elements from the array. The first form returns nil, If the array is empty .

How do I remove a specific element from an array in Ruby?

Ruby | Array delete() operation Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array. delete() Parameter: obj - specific element to delete Return: last deleted values from the array.

What does .last do in Ruby?

The . last property of an array in Ruby returns the last element of the array.

What does .shift do in Ruby?

The shift() is an inbuilt function in Ruby returns the element in the front of the SizedQueue and removes it from the SizedQueue. Parameters: The function does not takes any element.


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]

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

Another cool trick

>> *a, b = [1,2,3]
=> [1, 2, 3]
>> a
=> [1, 2]
>> b
=> 3

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]

I do it like this:

my_array[0..-2]