2009-05-19 47 views
0

我試圖製作一個小腳本來評估Ruby中的修補後表達式。Ruby中的「評估Postfix表達式」程序

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」)函數?

回答

2

,整數()是一種優雅的方式來做到這一點,因爲它可以確保你的整數定義匹配紅寶石的。如果你不想使用它,因爲它會拋出異常,正則表達式很好地工作 - 爲什麼要避免它們?另外,請注意,在整數情況下,您可以簡單地將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 
+0

謝謝。我去做。 – unj2 2009-05-19 22:23:26