我正在创建一个反向波兰符号计算器作为学校的“热身测试”。我几乎已经搞定了。我遇到的问题是当我自己运行它时,我只看到返回的整数(这是所需的)。当我将它插入学校的 RSpec 检查器时,它会以数组的形式返回我的数据,因此它被标记为不正确。
为了解决这个问题,我只是在最后构建了 queue.each 语句。我在几个不同的位置上试过这个,但这似乎并不重要。当评估返回答案时,是否有更大的概念可以从数组格式中提取我的答案?
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
提前感谢您的时间,