Last active
April 14, 2016 18:29
-
-
Save durrellchamorro/97206f0f903809d43f15b8ad386b7a37 to your computer and use it in GitHub Desktop.
Wordy
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(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