Created
November 20, 2014 11:26
-
-
Save riseshia/30e3d06762625aaaa0db to your computer and use it in GitHub Desktop.
Simple calculator with regexp
This file contains 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
def cal(expr) | |
while(true) | |
matched = /(\d+)(\*)(\d+)/.match(expr) | |
expr.gsub!(matched[0],"#{matched[1].to_i * matched[3].to_i}") if matched | |
matched = /(\d+)(\/)(\d+)/.match(expr) | |
return "Error!" if matched and matched[3] == "0" | |
expr.gsub!(matched[0],"#{matched[1].to_i / matched[3].to_i}") if matched | |
matched = /(\d+)(\+)(\d+)/.match(expr) | |
expr.gsub!(matched[0],"#{matched[1].to_i + matched[3].to_i}") if matched | |
matched = /(\d+)(\-)(\d+)/.match(expr) | |
expr.gsub!(matched[0],"#{matched[1].to_i - matched[3].to_i}") if matched | |
break unless matched | |
end | |
expr | |
end | |
def test(expr, expected) | |
old = expr.clone | |
actual = cal(expr) | |
if actual == expected | |
puts "[PASS] #{old} is #{actual}" | |
else | |
puts "[FAIL] #{old} expected #{expected} but #{actual}" | |
end | |
end | |
test("4-2","2") | |
test("2+3","5") | |
test("3*4","12") | |
test("6/2","3") | |
test("3/0","Error!") | |
test("2+4*2","10") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment