Last active
August 29, 2015 14:06
-
-
Save wjessop/20da252ca3a3d8def0f4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment