-
-
Save garciadanny/5100741 to your computer and use it in GitHub Desktop.
REGULAR EXPRESSIONS
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
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