Skip to content

Commit

Permalink
eighth step on ruby language
Browse files Browse the repository at this point in the history
  • Loading branch information
jrdi committed Oct 30, 2011
1 parent b3d0034 commit 26c5fe0
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions jrdi/string_calculator.rb
Expand Up @@ -2,15 +2,21 @@

class StringCalculator

def self.add(string)
delimiter = string.match(%r{^\/\/\[(.+)\]\\n}) && $1 || ','
def self.add(string)

numbers = string.split(%r{[\\n, #{delimiter}]}).map(&:to_i).delete_if {|i| i > 1000}
delimiters = if delimiter = (string.match(%r{^\/\/\[(.+)\]\\n}) && $1)
delimiter.split('][')
else
[',']
end

numbers = string.split(%r{#{delimiters + ['\n']}}).map(&:to_i).delete_if {|i| i > 1000}

negatives = numbers.select {|number| number < 0}
raise "Negatives numbers not allowed: #{negatives.join(', ')}" if negatives.any?

numbers.inject(0) {|total, number| total += number }
return 0 if numbers.empty?
numbers.reduce(:+)
end

end
Expand Down Expand Up @@ -51,4 +57,8 @@ def self.add(string)
it "should return 3 for '//[;;;]\n1;;;2'" do
StringCalculator.add('//[;;;]\n1;;;2').should == 3
end

it "should return 7 for '//[;;;][***]\n1;;;2***4'" do
StringCalculator.add('//[;;;][***]\n1;;;2***4').should == 7
end
end

0 comments on commit 26c5fe0

Please sign in to comment.