Skip to content

Instantly share code, notes, and snippets.

@Scoutski
Created October 11, 2015 23:25
Show Gist options
  • Save Scoutski/b1e864da98256d98e249 to your computer and use it in GitHub Desktop.
Save Scoutski/b1e864da98256d98e249 to your computer and use it in GitHub Desktop.
I promise this was the last wordy calculator (Solution)
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