Skip to content

Instantly share code, notes, and snippets.

@marioaquino
Created September 22, 2010 12:50
Show Gist options
  • Save marioaquino/591607 to your computer and use it in GitHub Desktop.
Save marioaquino/591607 to your computer and use it in GitHub Desktop.
module Calculator
def self.calculate(expression)
raise ArgumentError, 'Must be a string expression' unless expression.is_a? String
raise ArgumentError, 'Must be numeric arithmetic' unless expression =~ /\d\s[\+\-\*\/]\s\d/
parts = []
expression.split(/\s/).each do |val|
parts << val
if parts.size == 3
result = parts[0].to_i.send(parts[1].to_sym, parts[2].to_i)
parts.replace([result])
end
end
parts[0].to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment