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
- この大雑把な方法または正規表現を使用せずに、式の文字が整数であるかどうかを確認するより良い方法を知りません。何か提案はありますか?
- ケースを抽象化する方法はありますか。Rubyにeval("num1 ch num2")関数はありますか?