Skip to content

Instantly share code, notes, and snippets.

@jpcaruana
Created October 31, 2012 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpcaruana/3986486 to your computer and use it in GitHub Desktop.
Save jpcaruana/3986486 to your computer and use it in GitHub Desktop.
Reverse Polish notation (ruby)
require "test/unit"
OPERATIONS = {
"+" => lambda { |a, b| a + b },
"-" => lambda { |a, b| a - b },
"*" => lambda { |a, b| a * b },
"/" => lambda { |a, b| a / b }
}
def eval_polish(expression)
elements = expression.split
stack = []
elements.each { |element|
if OPERATIONS.keys.include? element
b = stack.pop
a = stack.pop
stack.push OPERATIONS[element].call a, b
else
stack.push element.to_i
end
}
stack.pop
end
class PolishTest < Test::Unit::TestCase
def test_soustraction
assert_equal 1, eval_polish('3 2 -')
assert_equal 3, eval_polish('5 2 -')
end
def test_addition
assert_equal 5, eval_polish('3 2 +')
end
def test_addition_2_etages
assert_equal 6, eval_polish('3 2 1 + +')
end
def test_multiplication
assert_equal 6, eval_polish('3 2 *')
end
def test_division
assert_equal 2, eval_polish('4 2 /')
end
def test_acceptance
assert_equal 2, eval_polish('4 2 5 * + 1 3 2 * + /')
assert_equal 14, eval_polish('5 1 2 + 4 * 3 - +')
end
end
@jbpotonnier
Copy link

Same, using functional style :
https://gist.github.com/3976975#file_postfix.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment