Skip to content

Instantly share code, notes, and snippets.

@durrellchamorro
Last active April 14, 2016 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durrellchamorro/97206f0f903809d43f15b8ad386b7a37 to your computer and use it in GitHub Desktop.
Save durrellchamorro/97206f0f903809d43f15b8ad386b7a37 to your computer and use it in GitHub Desktop.
Wordy
class WordProblem
def initialize(string)
@problem = string
end
def answer
operations = extract_operations @problem
fail ArgumentError, 'Valid operations: plus, minus, multiplied or divided' if operations.empty?
numbers = extract_numbers @problem
index = 0
numbers.inject do |memo, number|
memo = memo.send(operation(operations[index]), number)
index += 1
memo
end
end
private
def extract_numbers(problem)
array_of_strings = problem.scan(/-?\d+/)
array_of_strings.map(&:to_i)
end
def operation(string)
if string == 'plus'
:+
elsif string == 'minus'
:-
elsif string == 'multiplied'
:*
else
:/
end
end
def extract_operations(problem)
problem.scan(/plus|minus|multiplied|divided/)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment