Using Ruby arrays as stacks and queues.

  • array.push appends an element to the array.
  • array.pop removes (and returns) the last element in the array.
  • Hence array.last (and array[-1]) operates like array.peek would if it existed--it returns (but does not remove) the item on the top of the stack.
  • array.shift removes (and returns) the first element in the array.
  • Hence array.shift "pops" an element in a queue-like way--first in, first out. array.first (and array[1]) allow one to "peek" at this element.
> a = [ 1, 2, 3 ]         # => [1, 2, 3]
> a.push 4                # => [1, 2, 3, 4]
> a.pop                   # => 4
> a                       # => [1, 2, 3]
> a.last                  # => 3
> a                       # => [1, 2, 3]
> a.shift                 # => 1
> a                       # => [2, 3]
> a.first                 # => 2
Tagged ruby and dev.

 

This page was generated at 4:16 PM on 26 Feb 2018.
Copyright © 1999 - 2018 Rodney Waldhoff.