Skip to content

Instantly share code, notes, and snippets.

@dgamboa
Created September 7, 2012 16:03
Show Gist options
  • Select an option

  • Save dgamboa/3667422 to your computer and use it in GitHub Desktop.

Select an option

Save dgamboa/3667422 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator
# The following method will take strings like '5 4 +', '-1', '5 -3 4 + 6 9 - * +', and '2 3 4 7 + * -', and return the result of running the calculation.
# Note: when performing division it will always round down.
def evaluate(string)
return string.to_i unless string.include?(' ')
string.match /(-?\d+) (-?\d+) ([-+*\/])(?!\d)/
result = ($1.to_i).send($3,$2.to_i)
string.gsub!($1 + ' ' + $2 + ' ' + $3, result.to_s)
evaluate(string)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment