Skip to content

Instantly share code, notes, and snippets.

@juandefelix
Last active August 29, 2015 14:02
Show Gist options
  • Save juandefelix/02f22b8599c0b12c9654 to your computer and use it in GitHub Desktop.
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
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
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