-4

I have an array like:

a = Array.new([1,2,3,4,5,5,6,6,7,8])

By doing the following, I expect the output to be the zeroth index, which is popped out of the array.

a.pop
a.pop(0)

I am getting the output nil. Please give some suggestions on this behaviour.

ucMedia
  • 4,105
  • 4
  • 38
  • 46

2 Answers2

4

The optional argument to pop is not the index to pop from but the number of elements to pop. They are always taken from the end of the array.

To take from the beginning you need shift.

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
3

.pop is removing elements from the right. To remove elements from the left, use .shift

a.shift
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367