Created
June 20, 2011 03:09
-
-
Save frnz/1035060 to your computer and use it in GitHub Desktop.
String calculator
This file contains hidden or 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
module StringCalculator | |
def add | |
return 0 if empty? | |
raise "Negatives not allowed: #{ negative_numbers.join(",") }" unless negative_numbers.empty? | |
retrieve_numbers.reduce(0) {|total,number|total+number} | |
end | |
def retrieve_numbers | |
@retrieve_numbers ||= split(/[\n#{delimiter}]/).map(&:to_i) | |
end | |
def negative_numbers | |
@negative_numbers ||= retrieve_numbers.select {|number| number < 0} | |
end | |
def delimiter | |
self[0,2] == "//" ? self[2,1] : "," | |
end | |
end |
This file contains hidden or 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
require File.join(File.dirname(__FILE__), "../lib/string_calculator") | |
describe StringCalculator do | |
before :all do | |
class String | |
include StringCalculator | |
end | |
end | |
it "returns 0 for empty string" do | |
"".add.should == 0 | |
end | |
context "1 number" do | |
it "returns 0 for 0" do | |
"0".add.should == 0 | |
end | |
it "returns 2 for 2" do | |
"2".add.should == 2 | |
end | |
end | |
context "more than 1 number" do | |
it "can sum 2 numbers" do | |
"1,2".add.should == 3 | |
end | |
it "can sum 3 numbers" do | |
"1,2,3".add.should == 6 | |
end | |
it "can sum 100 numbers" do | |
(1..100).to_a.join(",").add.should == 5050 | |
end | |
end | |
context "delimiters" do | |
it "sums numbers separated by commas" do | |
"2,3".add.should == 5 | |
end | |
it "sums numbers separated by newline" do | |
"5\n3".add.should == 8 | |
end | |
it "can have a custom delimiter" do | |
"//;\n3;3".add.should == 6 | |
end | |
it "supports mixed delimiters" do | |
"2,3\n4".add.should == 9 | |
end | |
it "supports mixed delimiters using a custom delimiter" do | |
"//;\n3;3\n2".add.should == 8 | |
end | |
it "supports minus as a custom delimiter" do | |
"//-\n2-3-3".add.should == 8 | |
end | |
end | |
context "negative numbers" do | |
it "raises an error if there's a negative number" do | |
lambda { "-1,2".add }.should raise_error | |
end | |
it "shows negative numbers in the error message" do | |
lambda { "-1,2,-3".add }.should raise_error("Negatives not allowed: -1,-3") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment