-
-
Save Scoutski/b1e864da98256d98e249 to your computer and use it in GitHub Desktop.
I promise this was the last wordy calculator (Solution)
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 | |
def initialize question | |
@question = question | |
end | |
def answer | |
if matches.nil? | |
raise ArgumentError.new( "Sorry, please enter a valid question." ) | |
end | |
@answer = matches[1].to_i.send( operation(2), matches[3].to_i ) | |
unless chain.nil? | |
@answer = @answer.send( operation(5), matches[6].to_i) | |
end | |
@answer | |
end | |
private | |
def matches | |
@matches = @question.match( pattern ) | |
end | |
def pattern | |
/What is (-?\d+) (plus|minus|multiplied by|divided by) (-?\d+)( (plus|minus|multiplied by|divided by) (-?\d+))?\?/ | |
end | |
def operation num | |
case matches[ num ] | |
when "plus" then :+ | |
when "minus" then :- | |
when "multiplied by" then :* | |
when "divided by" then :/ | |
end | |
end | |
def chain | |
matches[4] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment