Created
December 2, 2009 20:16
-
-
Save cored/247525 to your computer and use it in GitHub Desktop.
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 StringCalculator | |
def add(numbers) | |
return 0 if numbers.empty? | |
raise ArgumentError if is_negative?(numbers) | |
return handle_more_than_one_number(extract_numbers(numbers), extract_delimiter(numbers)) if has_optional_delimiter(numbers) | |
return handle_more_than_one_number(numbers, ",") if has_more_than_one_number?(numbers) | |
return numbers.to_i | |
end | |
def is_negative?(numbers) | |
numbers.index "-" | |
end | |
def extract_numbers(numbers) | |
numbers[4,numbers.size] | |
end | |
def extract_delimiter(numbers) | |
numbers[2,1] | |
end | |
def has_more_than_one_number?(numbers) | |
numbers.index ',' | |
end | |
def has_optional_delimiter(numbers) | |
numbers.index '//' | |
end | |
def handle_more_than_one_number(numbers, delimiter) | |
numbers.gsub! "\n", delimiter | |
numbers.split(delimiter).inject(0) { |sum, num| sum + num.to_i } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment