Last active
August 26, 2015 19:57
-
-
Save simonswine/826e0a3acc9bb2b256cf to your computer and use it in GitHub Desktop.
StringCalc in ruby
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
class StringCalc | |
def self.calc(str) | |
# default regex to split | |
re_split = %r{[\n,]} | |
# regex for custom delimiter | |
m = str.match(%r{^//(.)}) | |
re_split = %r{#{m[1]}} if m | |
# sum initial val | |
sum = 0 | |
str.split(re_split).each do |v| | |
sum += v.to_i | |
end | |
sum | |
end | |
end | |
describe StringCalc do | |
describe ".calc" do | |
subject do | |
StringCalc | |
end | |
it 'returns 0 if empty input' do | |
expect(subject.calc("")).to eq(0) | |
end | |
describe 'comma delimiter' do | |
it 'returns 0 if delimiter only input' do | |
expect(subject.calc(",")).to eq(0) | |
end | |
it 'returns correct sum of elements' do | |
expect(subject.calc("1,2,3,4")).to eq(10) | |
end | |
it 'returns correct sum of elements' do | |
expect(subject.calc("1,2")).to eq(3) | |
end | |
end | |
describe 'newline delimiter' do | |
it 'returns 0 if delimiter only input' do | |
expect(subject.calc("\n\n\n")).to eq(0) | |
end | |
it 'returns correct sum of elements' do | |
expect(subject.calc("1\n2\n3\n4")).to eq(10) | |
end | |
it 'returns correct sum of elements' do | |
expect(subject.calc("1\n2")).to eq(3) | |
end | |
end | |
describe 'mixed newline and comma delimiter' do | |
it 'returns 0 if delimiter only input' do | |
expect(subject.calc("\n,\n")).to eq(0) | |
end | |
it 'returns correct sum of elements' do | |
expect(subject.calc("1,2\n3,4")).to eq(10) | |
end | |
it 'returns correct sum of elements' do | |
expect(subject.calc("1\n2,3")).to eq(6) | |
end | |
end | |
describe 'custom delimiter' do | |
it 'returns correct sum of elements' do | |
expect(subject.calc("//|\n1|2|3|4")).to eq(10) | |
end | |
it 'returns correct sum of elements' do | |
expect(subject.calc("//\n\n1\n2\n3")).to eq(6) | |
end | |
it 'returns correct sum of elements' do | |
expect(subject.calc("//-\n1-2-3-4-5")).to eq(15) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment