Class: Algorithms::Containers::Stack
- Inherits:
-
Object
- Object
- Algorithms::Containers::Stack
- Includes:
- Enumerable
- Defined in:
- lib/containers/stack.rb
Instance Method Summary collapse
-
#each(&block) ⇒ Object
Iterate over the Stack in LIFO order.
-
#empty? ⇒ Boolean
Returns true if the stack is empty, false otherwise.
-
#initialize(ary = []) ⇒ Stack
constructor
Create a new stack.
-
#next ⇒ Object
Returns the next item from the stack but does not remove it.
-
#pop ⇒ Object
Removes the next item from the stack and returns it.
-
#push(obj) ⇒ Object
(also: #<<)
Adds an item to the stack.
-
#size ⇒ Object
Return the number of items in the stack.
Constructor Details
#initialize(ary = []) ⇒ Stack
Create a new stack. Takes an optional array argument to initialize the stack.
s = Algorithms::Containers::Stack.new([1, 2, 3])
s.pop #=> 3
s.pop #=> 2
18 19 20 |
# File 'lib/containers/stack.rb', line 18 def initialize(ary=[]) @container = Deque.new(ary) end |
Instance Method Details
#each(&block) ⇒ Object
Iterate over the Stack in LIFO order.
65 66 67 |
# File 'lib/containers/stack.rb', line 65 def each(&block) @container.each_backward(&block) end |
#empty? ⇒ Boolean
Returns true if the stack is empty, false otherwise.
60 61 62 |
# File 'lib/containers/stack.rb', line 60 def empty? @container.empty? end |
#next ⇒ Object
Returns the next item from the stack but does not remove it.
s = Algorithms::Containers::Stack.new([1, 2, 3])
s.next #=> 3
s.size #=> 3
27 28 29 |
# File 'lib/containers/stack.rb', line 27 def next @container.back end |
#pop ⇒ Object
Removes the next item from the stack and returns it.
s = Algorithms::Containers::Stack.new([1, 2, 3])
s.pop #=> 3
s.size #=> 2
47 48 49 |
# File 'lib/containers/stack.rb', line 47 def pop @container.pop_back end |
#push(obj) ⇒ Object Also known as: <<
Adds an item to the stack.
s = Algorithms::Containers::Stack.new([1])
s.push(2)
s.pop #=> 2
s.pop #=> 1
37 38 39 |
# File 'lib/containers/stack.rb', line 37 def push(obj) @container.push_back(obj) end |
#size ⇒ Object
Return the number of items in the stack.
s = Algorithms::Containers::Stack.new([1, 2, 3])
s.size #=> 3
55 56 57 |
# File 'lib/containers/stack.rb', line 55 def size @container.size end |