class Grizzled::Stack
A simple stack wrapper on top of a Ruby array, providing a little more protection that using an array directly.
Attributes
Public Class Methods
Initialize a new stack.
Parameters:
- #pop_empty_nil
-
true
if popping an empty stack should just returnnil
,false
if it should thrown an exception.
# File lib/grizzled/stack.rb, line 58 def initialize(pop_empty_nil=true) @the_stack = [] @pop_empty_nil = pop_empty_nil end
Public Instance Methods
Compare this stack to another element.
# File lib/grizzled/stack.rb, line 149 def <=>(other) if other.class == Stack other.to_a <=> to_a else other.to_s <=> this.to_s end end
Clear the stack. Returns the stack, for chaining.
# File lib/grizzled/stack.rb, line 123 def clear @the_stack.clear self end
Yield each element of the stack, in turn. Unaffected by a change in the stack.
# File lib/grizzled/stack.rb, line 116 def each self.to_a.each do |element| yield element end end
Determine if this hash is equal to another one.
# File lib/grizzled/stack.rb, line 144 def eql?(other) (other.class == Stack) and (other.to_a == to_a) end
Return the stack's hash.
# File lib/grizzled/stack.rb, line 139 def hash @the_stack.hash end
Printable version.
# File lib/grizzled/stack.rb, line 129 def inspect @the_stack.inspect end
Convenience method for +length == 0+.
# File lib/grizzled/stack.rb, line 82 def is_empty? length == 0 end
Returns the size of the stack.
# File lib/grizzled/stack.rb, line 110 def length @the_stack.length end
Pop the top element from the stack. If the stack is empty, this method
throws a StackUnderflowException
, if
pop_empty_nil
is false
; or returns nil, if
pop_empty_nil
is true
.
# File lib/grizzled/stack.rb, line 66 def pop if (@the_stack.length == 0) && (not @pop_empty_nil) raise StackUnderflowException.new end @the_stack.pop end
Pop every element of the stack, returning the results as an array and clearing the stack.
# File lib/grizzled/stack.rb, line 75 def pop_all result = @the_stack.reverse @the_stack.clear result end
Push an element or an array of elements onto the stack. Returns the stack itself, to allow chaining. Note: If you push an array of elements, the elements end up being reversed on the stack. That is, this:
stack = Stack.new.push([1, 2, 3]) # yields Stack[3, 2, 1]
is equivalent to
stack = Stack.new [1, 2, 3].each {|i| stack.push i}
Parameters:
- element
-
The object to push onto the stack.
# File lib/grizzled/stack.rb, line 100 def push(element) if element.class == Array element.each {|e| @the_stack.push e} else @the_stack.push element end self end
Return the stack as an array.
# File lib/grizzled/stack.rb, line 134 def to_a @the_stack.reverse end