-1

I'm creating a reverse polish notation calculator as a 'warm-up test' for school. I've almost nailed it. The issue I'm coming across is when I run this myself, I see just the integer returned (which is desired). When I plug this into the school's RSpec checker it returns my data in an array, so it's flagged as incorrect.

To fix, I just built the queue.each statement on the end. I tried this in a few different positions, but it does not seem to matter. Is there a bigger concept to extract my answer out of the array format when evaluate returns an answer?

class RPNCalculator

    def evaluate(string)
        holding = []
        queue = []
        string = string.split(" ").to_a      #jam string into an array - break on spaces

        string.each do |x|
            if x.match(/\d/)      #number checker. if true throw it in queue.
             queue << x.to_i       #convert to number from string
            elsif x.match(/\+/)      #math operator checker
                holding << queue[-2] + queue[-1]     #grab queue's last 2 & replace w/ result
                queue.pop(2)
                queue << holding[-1]
            elsif x.match(/\-/)
                holding << queue[-2] - queue[-1]
                queue.pop(2)
                queue << holding[-1]    
            elsif x.match(/\*/) 
                holding << queue[-2] * queue[-1]
                queue.pop(2)
                queue << holding[-1]    
            else
            end
        end
            return queue.each { |x| puts x.to_i}     # by [-1] in string, queue holds answer
    end
end

Thank you in advance for your time,

CJ Johnson
  • 1,081
  • 9
  • 13
  • Why are using an array for `holding`? It looks like you are always pushing to it, then using its last element. Why can't it simply be a variable? – sawa Aug 19 '14 at 02:59

1 Answers1

0

Your method (without queue.each) is returning the result of string.each.

If you want to return queue, you need to do that.

class RPNCalculator

    def evaluate(string)
        holding = []
        queue = []
        string = string.split(" ").to_a      #jam string into an array - break on spaces

        string.each do |x|
          #...
        end
        queue[0] # return the final result, stored in queue
    end
end
user229044
  • 232,980
  • 40
  • 330
  • 338