Class: CollectionUtils::Stack

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

Instance Method Summary collapse

Constructor Details

#initialize(array = []) ⇒ Stack

Constructors



8
9
10
11
12
13
# File 'lib/collection_utils/stack.rb', line 8

def initialize(array=[])
  @stack = []
  array.each do |element|
    @stack << element
  end
end

Instance Method Details

#is_empty?Boolean

Returns stack’s emptiness.

Examples:

Create a stack [1,2,3,4,5] and add check emptiness.

stack = CollectionUtils::Stack.new([1,2,3,4,5])
stack.is_empty? # false

Returns:

  • (Boolean)

    stack’s emptiness



42
43
44
# File 'lib/collection_utils/stack.rb', line 42

def is_empty?
  return @stack.size == 0
end

#peekObject

View the top element of the stack without removing it

Examples:

Create a stack [1,2,3,4,5] and get 5 using peek

stack = CollectionUtils::Stack.new([1,2,3,4,5])
top_element = stack.peek # top_element = 5, stack = [1,2,3,4,5]

Returns:

  • Top element of the stack



53
54
55
# File 'lib/collection_utils/stack.rb', line 53

def peek
  return @stack.last
end

#popObject

Pop will remove the top element from the stack and return the removed element.

Examples:

Create a stack [1,2,3,4,5] and remove 5 using pop

stack = CollectionUtils::Stack.new([1,2,3,4,5])
top_element = stack.pop() # top_element = 5, stack = [1,2,3,4]

Returns:

  • Top element of the stack



22
23
24
# File 'lib/collection_utils/stack.rb', line 22

def pop
  return @stack.pop
end

#push(element) ⇒ Object

Add the element to the stack using push

Examples:

Create a stack [1,2,3,4,5] and add 6 to it.

stack = CollectionUtils::Stack.new([1,2,3,4,5])
stack.push(6)
#stack will be [1,2,3,4,5,6]

Parameters:

  • element

    that needs to added to stack. This element will the top element



34
35
36
# File 'lib/collection_utils/stack.rb', line 34

def push(element)
  @stack << element
end

#sizeInteger

Returns size of stack.

Examples:

Create a stack [1,2,3,4,5] and check size.

stack = CollectionUtils::Stack.new([1,2,3,4,5])
stack.size # 5

Returns:

  • (Integer)

    size of stack



61
62
63
# File 'lib/collection_utils/stack.rb', line 61

def size
  return @stack.size
end