0

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")関数はありますか?
4

2 に答える 2

2

文字列が整数かどうかを確認したい場合は、整数の定義がルビーの定義と一致することを確認するため、Integer() がエレガントな方法です。例外がスローされるため、それを使用したくない場合は、正規表現がうまく機能します-なぜそれらを避けるのですか? また、整数の場合、ch ではなく y をスタックにプッシュするだけでよく、ポップ時に to_i 呼び出しを行う必要がないことに注意してください。他の質問に関しては、ルビーには確かに 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  
于 2009-05-20T07:39:42.417 に答える