Class: RPNConverter

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

Instance Method Summary collapse

Instance Method Details

#close_parenObject



32
33
34
35
36
37
# File 'lib/rpn_converter.rb', line 32

def close_paren
  until (@stack.last == '(' ) do
    @output << @stack.pop
  end
  @stack.pop
end

#infix_to_rpn(exp) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/rpn_converter.rb', line 3

def infix_to_rpn(exp)
  @output = ''
  @stack = []
  string = exp.gsub(' ', '')
  string.each_char do |char|
    case char
    when /\w/ then @output << char
    when /\)/ then close_paren
    when /\(/ then @stack << char
    else operator(char)
    end
  end
  until @stack.empty? do
    @output << @stack.pop
  end
  @output.gsub(/[()]/, "")
end

#operator(char) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/rpn_converter.rb', line 39

def operator(char)
  while !@stack.empty? && precedence(char) <= precedence(@stack.last) do
    @output << @stack.pop
  end
  @output << ' ' if @output[@output.length - 1].match /\d/
  @stack << char
end

#precedence(op) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/rpn_converter.rb', line 21

def precedence(op)
  case op
  when /[+-]/
    1
  when /[\*\/]/
    2
  when /[()]/
    0
  end
end