Class: RubyStructures::Stack

Inherits:
Object
  • Object
show all
Defined in:
lib/rubystructures/stack.rb

Instance Method Summary collapse

Constructor Details

#initializeStack

Public: Creates a new instance of Stack with default values.

Examples

Stack.new

Returns a new instance of RubyStuctures::Stack.



10
11
12
# File 'lib/rubystructures/stack.rb', line 10

def initialize
	@storage = Array.new
end

Instance Method Details

#empty?Boolean

Public: Boolean check to see if the stack is empty.

Examples

@stack.empty? # => true

Returns true if the Stack is empty, false otherwise.

Returns:

  • (Boolean)


88
89
90
# File 'lib/rubystructures/stack.rb', line 88

def empty?
	@storage.size == 0
end

#popObject

Public: Removes and returns the value from the top of the stack.

Examples

# If the stack has :size > 1, return the top value. @stack.pop # => 42

# If the stack is empty, returns nil. @stack.pop # => nil

Returns the value at the top of the stack, or nil if the stack is empty.



59
60
61
# File 'lib/rubystructures/stack.rb', line 59

def pop
	@storage.pop
end

#push(value) ⇒ Object

Public: Adds value to the Stack.

value - Ruby data type, can be of any class type.

Examples

@stack.push(42) # => true

Returns true if the value was successfully added to the stack.



38
39
40
41
42
43
44
# File 'lib/rubystructures/stack.rb', line 38

def push(value)
	if @storage << value
		true
	else
		false
	end
end

#sizeObject

Public: Returns the Integer current size of the stack. We can rely on the Ruby Array to provide us with the correct stack size, which allows us to not have a :size instance variable.

Examples

@stack.size # => 42

Returns the size of the stack.



24
25
26
# File 'lib/rubystructures/stack.rb', line 24

def size
	@storage.size
end

#topObject

Public: Peek at the value on the top of the stack without removing it.

Examples

@stack.top # => 42

# If the stack is empty, returns nil. @stack.top # => nil

Returns the value at the stop of the Stack, but does not pop the value off the stack. Returns nil if the Stack is empty.



76
77
78
# File 'lib/rubystructures/stack.rb', line 76

def top
	@storage.last
end