Skip to content

Instantly share code, notes, and snippets.

@wjessop
Last active August 29, 2015 14:06
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 wjessop/20da252ca3a3d8def0f4 to your computer and use it in GitHub Desktop.
Save wjessop/20da252ca3a3d8def0f4 to your computer and use it in GitHub Desktop.
require "minitest/unit"
require 'minitest/autorun'
def calculate(str)
acc = state = 0
op = "+"
str.scan(/(?:.+?\b)/) do |atom|
if (state = 1 - state) == 1 # number state
acc = acc.send(op, Integer(atom))
else # op state
op = atom
end
end
return acc
rescue ArgumentError
return nil
end
class TestCalculate < MiniTest::Unit::TestCase
def test_calculate
assert_equal 9, calculate("4+5")
assert 20, calculate("10+8+2")
assert 5, calculate("10-5")
assert 9, calculate("10+2-4")
assert_nil calculate("12**12**1fsdaf2")
end
end
Run options: --seed 35201
# Running tests:
.
Finished tests in 0.001561s, 640.6150 tests/s, 3203.0750 assertions/s.
1 tests, 5 assertions, 0 failures, 0 errors, 0 skips
@caius
Copy link

caius commented Sep 24, 2014

def calculate(str)
  eval(str) if str[/\A[\s\d+\-\/\*]+\z/]
end

@wjessop
Copy link
Author

wjessop commented Sep 24, 2014

Eval wasn't allowed!

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