Last active
June 30, 2017 22:45
-
-
Save s2t2/9032d7677956f87830f1e70ed6aa31af to your computer and use it in GitHub Desktop.
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 "pry" | |
class Calculation | |
attr_accessor :equation | |
alias :eq :equation | |
# @param [String] equation An input string containing a math equation. | |
# The only supported operations are addition, subtraction, multiplication, and division. | |
# The equation is assumed to be valid, with spaces between operators, and all operands being numbers. | |
# | |
# @example | |
# Calculation.new("1 * 5") | |
# Calculation.new("1 + -1") | |
# Calculation.new("1 + 4 - 2") | |
# | |
def initialize(equation) | |
@equation = equation | |
end | |
OPERATORS = ["+", "-", "*", "/"] | |
def operands | |
eq.split(" ").delete_if{|str| OPERATORS.include?(str) } | |
end #> ["1", "4", "2"] | |
def operators | |
eq.split(" ").keep_if{|str| OPERATORS.include?(str) } | |
end #> ["+", "-"] | |
def calculate(left_side, operator, right_side) | |
left_side.send(operator, right_side) | |
end | |
def result | |
operators.each_with_index do |operator, i| | |
left_side = @memory || operands[i].to_f | |
right_side = operands[i + 1].to_f | |
@memory = calculate(left_side, operator, right_side) | |
end | |
return @memory | |
end | |
end | |
equations = [ | |
"1 * 5", | |
"1 + -1", | |
"1 - 5", | |
"10 / 3", | |
#"1 + 1.1", | |
#"1 - 1.1", | |
#"1 * 1.1", | |
#"1 / 1.1", | |
"1 + 4 - 2" | |
] | |
equations.each do |eq| | |
puts "#{eq} EQUALS #{Calculation.new(eq).result}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment