Skip to content

Instantly share code, notes, and snippets.

@cored
Created December 2, 2009 20:16
Show Gist options
  • Save cored/247525 to your computer and use it in GitHub Desktop.
Save cored/247525 to your computer and use it in GitHub Desktop.
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