Topic: Pop (array)

Is there any other way of writing for example

a.pop
a.pop

Re: Pop (array)

There is no dedicated function for what you describe as far as I know, although it could be done with the slice! method:

arr.slice!( arr.length - 2, arr.length - 1)

The first number can be changed to dictate how many items should be removed from the end of the array. Obviously this is not the neatest or most readable way of doing it, and it will fail if the numbers are out of range, or if the array is empty; so it might be worth putting into a function. But you get the general idea.

Alex

Re: Pop (array)

I want also the last popped value to be returned the same way as in

a.pop
a.pop

class Array
    def pop_several(n)
        t = nil
        n.times { t = self.pop }
        t
    end
end

a = [1, 2, 3, 4, 5]
a.pop_several(2)

Re: Pop (array)

If you don't need to alter the existing array, you can use "last".

a = [1, 2, 3, 4, 5]
a.last(2)
#=> [4, 5]

Railscasts - Free Ruby on Rails Screencasts

Re: Pop (array)

Johannes wrote:

I want also the last popped value to be returned the same way as in

a.pop
a.pop

class Array
    def pop_several(n)
        t = nil
        n.times { t = self.pop }
        t
    end
end

a = [1, 2, 3, 4, 5]
a.pop_several(2)

What I came up with is very similar to yours.  It returns the values popped in an array.

class Array
  def pop_last!(n)
    a = last(n)
    n.times { self.pop }
    a
  end
end

x = [1, 2, 3, 4, 5]
p x.pop_last!(2) #=> [4,5]
p x #=> [1,2,3]