Last active
August 29, 2015 14:02
-
-
Save juandefelix/02f22b8599c0b12c9654 to your computer and use it in GitHub Desktop.
Calculator. This method calculates the result of the basic mathematical operations in a string
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 calculator string | |
while string.match /[*\/]/ | |
# p string | |
string.gsub!(/(\d+)\s*([*\/])\s*(\d+)/) do |regex| | |
num1 = $1.to_i | |
num2 = $3.to_i | |
operator = $2.to_sym | |
"#{[num1, num2].reduce(operator)}" | |
end | |
end | |
while string.match /[-\+]/ | |
string.gsub!(/(\d+)\s*([-\+])\s*(\d+)/) do |regex| | |
num1 = $1.to_i | |
num2 = $3.to_i | |
operator = $2.to_sym | |
"#{[num1, num2].reduce(operator)}" | |
end | |
end | |
string.to_i | |
end |
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
require 'calculator' | |
describe "method calculator exist" do | |
it "calculator 2 + 3 == 5" do | |
expect(calculator("2 + 3")).to eq 5 | |
end | |
end | |
describe "method subtraction" do | |
it "10 - 5 == 5" do | |
expect(calculator("10 - 5")).to eq(5) | |
end | |
end | |
describe "method with multiple operators" do | |
it "10 - 5 == 5" do | |
expect(calculator("12 + 1 * 2 + 4 / 2")).to eq(16) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment