【问题标题】:"Evaluating Postfix Expressions" Program in RubyRuby 中的“评估后缀表达式”程序
【发布时间】:2009-05-19 22:11:27
【问题描述】:

我尝试制作一个小脚本来评估 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") 函数吗?

【问题讨论】:

    标签: ruby postfix-notation


    【解决方案1】:

    如果你想检查一个字符串是否是一个整数,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  
    

    【讨论】:

      【解决方案2】:

      我不知道红宝石,所以我不回答你的问题。但是,那里有一个算法问题。对于加法,乘以操作数的顺序无关紧要,但对于减法和除法,您应该将第一个操作数除以第二个操作数。第一个是堆栈更深的那个。因此,您应该交换这两行:

      num1 = my_stack.pop.to_i
      num2 = my_stack.pop.to_i
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-16
        • 2014-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多