Skip to content

Instantly share code, notes, and snippets.

@trobrock
Created May 24, 2012 00:22
Show Gist options
  • Save trobrock/2778589 to your computer and use it in GitHub Desktop.
Save trobrock/2778589 to your computer and use it in GitHub Desktop.
class Calculator
def exec(expression)
while op = expression.match(/\([^()]+\)/)
offsets = op.offset(0)
out = exec op[0].gsub(/[()]/,'')
expression[offsets.first...offsets.last] = out.to_s
end
while op = expression.match(/\d+ ?[\*\/] ?\d+/)
run_expression op, expression
end
while op = expression.match(/\d+ ?[\+\-] ?\d+/)
run_expression op, expression
end
expression.to_i
end
private
def run_expression(expression, full_expression)
offsets = expression.offset(0)
first, operator, second = expression[0].match(/(\d+) ?([+\-*\/]) ?(\d+)/).to_a[1..-1]
# p "#{first} #{operator} #{second}"
first = first.to_i
second = second.to_i
output = case operator
when "+"
first + second
when "-"
first - second
when "*"
first * second
when "/"
first / second
end
full_expression[offsets.first...offsets.last] = output.to_s
end
end
RSpec.configure do |config|
config.color_enabled = true
end
require File.join(File.dirname(__FILE__), 'calc')
describe Calculator do
before(:each) do
@calc = Calculator.new
end
it "should return 2" do
@calc.exec("1 + 1").should == 2
end
it "should return 4" do
@calc.exec("1 + 1 + 2").should == 4
end
it "should return 3" do
@calc.exec("1 + 1 * 2").should == 3
end
it "should return 2" do
@calc.exec("1 + 1 * 2 - 1").should == 2
end
it "should return 8" do
@calc.exec("(2 * 5) - (1 * 2)").should == 8
end
it "should return 4" do
@calc.exec("(((2 * 5) - (1 * 2)) / (11 - 9))").should == 4
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment