Skip to content

Instantly share code, notes, and snippets.

@s2t2
Last active June 30, 2017 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s2t2/9032d7677956f87830f1e70ed6aa31af to your computer and use it in GitHub Desktop.
Save s2t2/9032d7677956f87830f1e70ed6aa31af to your computer and use it in GitHub Desktop.
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