我尝试制作一个小脚本来计算 Ruby 中的后修复表达式。

def evaluate_post(expression)

    my_stack = Stack.new

    expression.each_char do |ch|        
    begin    
        # Get individual characters and try to convert it to integer
        y = Integer(ch)

        # If its an integer push it to the stack
        my_stack.push(ch)

    rescue    
        # If its not a number then it must be an operation
        # Pop the last two numbers
        num2 = my_stack.pop.to_i            
        num1 = my_stack.pop.to_i


        case ch
        when "+"   
            answer = num1 + num2        
        when "*"       
            answer = num1* num2    
        when "-"        
            answer = num1- num2     
        when "/"        
            answer = num1/ num2    
        end   

        # If the operation was other than + - * / then answer is nil
        if answer== nil
        my_stack.push(num2)
        my_stack.push(num1)
        else
        my_stack.push(answer)
        answer = nil
        end
    end
    end

    return my_stack.pop
end
  1. 我不知道在不使用这种粗略方法或正则表达式的情况下检查表达式中的字符是否为整数的更好方法。你们有什么建议吗?
  2. 有没有办法抽象案例。Ruby 中有 eval("num1 ch num2") 函数吗?
有帮助吗?

解决方案

如果你想检查一个字符串是否是一个整数,Integer() 是一种优雅的方法,因为它可以确保你对整数的定义与 ruby​​ 的相匹配。如果您不想使用它,因为它会引发异常,那么正则表达式可以很好地工作 - 为什么要避免它们?另请注意,在整数情况下,您可以简单地将 y 推入堆栈,而不是 ch,并且在弹出时不需要 to_i 调用。至于另一个问题,ruby确实有一个eval。

y = Integer(ch) rescue nil   
if y  
  stack.push(y)  
else  
  num2, num1 = stack.pop(2)  
  a = eval "#{num2} #{ch} #{num1}" # see mehrdad's comment for why not num1 ch num2  
  stack.push(a)  
end  

其他提示

我不懂ruby所以我不回答你的问题。不过,这里存在一个算法问题。对于加法、乘法操作数的顺序并不重要,但对于减法和除法,您应该将第一个操作数减去并除以第二个操作数。第一个是堆栈中较深的一个。因此,您应该交换这两行:

num1 = my_stack.pop.to_i
num2 = my_stack.pop.to_i
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top