Skip to content

Instantly share code, notes, and snippets.

@garciadanny
Forked from jcasimir/word_problem.rb
Created March 6, 2013 16:41
Show Gist options
  • Save garciadanny/5100741 to your computer and use it in GitHub Desktop.
Save garciadanny/5100741 to your computer and use it in GitHub Desktop.
REGULAR EXPRESSIONS
class WordProblem
attr_reader :equation
def initialize(equation)
@equation = equation
end
def answer
calculate
end
def calculate
# equation = 'What is 1 plus 1?'
matches = equation.scan /.* (-?\d+) (plus|minus|multiplied|divided)(?: by)? (-?\d+)/
first, operator, second = matches.first
op = operator_for(operator)
(first.to_i).send(op, second.to_i)
end
def operator_for(input)
if input == "plus"
:+
elsif input == "multiplied"
:*
elsif input == "divided"
:/
elsif input == "minus"
:-
else
raise ArgumentError
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment