Snippets are tiny notes I've collected for easy reference.
Using Ruby arrays as stacks and queues.
array.pushappends an element to the array.array.popremoves (and returns) the last element in the array.- Hence
array.last(andarray[-1]) operates likearray.peekwould if it existed--it returns (but does not remove) the item on the top of the stack. array.shiftremoves (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(andarray[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
Snippets are tiny notes I've collected for easy reference.
