Class: MathNotation

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string, type) ⇒ MathNotation

Returns a new instance of MathNotation.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/calculo/math.rb', line 9

def initialize(string,type)
        @string = string
        if type == 'infix'
                @type = 'rpn'
                @array = shunting_yard(parse(@string))
                @result = eval_rpn(@array)
        else
                @array = parse(@string)
                @type = type
                if @type == 'prefix' or @type == 'pn'
                        @result = eval_pn(@array)
                elsif @type == 'postfix' or @type == 'rpn'
                        @result = eval_rpn(@array)
                end
        end
end

Instance Attribute Details

#arrayObject

Returns the value of attribute array.



6
7
8
# File 'lib/calculo/math.rb', line 6

def array
  @array
end

#resultObject

Returns the value of attribute result.



7
8
9
# File 'lib/calculo/math.rb', line 7

def result
  @result
end

#stringObject

Returns the value of attribute string.



5
6
7
# File 'lib/calculo/math.rb', line 5

def string
  @string
end

#typeObject

Returns the value of attribute type.



4
5
6
# File 'lib/calculo/math.rb', line 4

def type
  @type
end

Instance Method Details

#eval_pn(array) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/calculo/math.rb', line 27

def eval_pn(array)
        operators = ['+','-','^','%','/','**','*']
        stack = []
        array.reverse.each{|item|
                if operators.include?(item)
                        num2,num1 = stack.pop(2)
                        result = num1.method(item).call(num2)
                        stack.push(result)
                else
                        stack.push(item)
                end
        }
        return stack.pop
end

#eval_rpn(array) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/calculo/math.rb', line 42

def eval_rpn(array)
        operators = ['+','-','^','%','/','**','*']
        stack = []
        array.each{|item|
                if operators.include?(item)
                        num1,num2 = stack.pop(2)
                        result = num1.method(item).call(num2)
                        stack.push(result)
                else
                        stack.push(item)
                end
        }
        return stack.pop
end