Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mi Kata de enero usando ruby #70

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions agutierrez/string_calculator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class StringCalculator

DEFAULT_DELIMITER = ","

def add(raw_string)
return 0 if raw_string.empty?
cleaned_string = clean_string(raw_string)
addends = extract_addends(cleaned_string)
addends.reduce(:+)
end # add

def clean_string(dirty_string)
new_string = dirty_string
if dirty_string[0] == "\\" then
delimiters = extract_delimiters(dirty_string[1..dirty_string.index("\n")-1])
new_string = dirty_string[dirty_string.index("\n")+1..dirty_string.length-1]
delimiters.each { |de| new_string.gsub!(de,DEFAULT_DELIMITER) }
end
new_string = new_string.gsub("\n", DEFAULT_DELIMITER)
end

def extract_delimiters(delimiter_string)
return delimiter_string.gsub("][", " ").gsub(/[\[,\]]/, "").split
end

def extract_addends(addends_string)
working_array = addends_string.split(DEFAULT_DELIMITER).collect { |a| a.to_i }
negatives = []
working_array.each { |wa| negatives << wa if wa < 0 }
working_array.delete_if { |wa| wa > 999 }
raise "No negatives allowed: #{negatives.join(', ')}" if !negatives.empty?
return working_array
end

end # class
31 changes: 31 additions & 0 deletions agutierrez/string_calculator_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
require './string_calculator'

describe 'StringCalculator', '#add' do

before(:each) do
@kata = StringCalculator.new
end

Kata_Data = [
["Should return 0 with an empty string", "", 0],
["Should return an integer with a text number", "2", 2],
["Should return the sum of two numbers separated by a comma", "2,3", 5],
["Should accept \n as a valid separator", "2\n3,5", 10],
["Should accept custom char separator between \\ and \n", "\\**\n2,3**4", 9],
["Should ignore numbers greater than 1000", "2,1002,6", 8],
["Should allow multiple delimiters between []", "\\[**][;]\n2**;5;6", 13]
]

Kata_Data.each do |kataItem|

it kataItem[0] do
@kata.add(kataItem[1]).should == kataItem[2]
end

end

it "Should raise an error if there is a negative" do
lambda{@kata.add("1,-2,4,-5")}.should raise_error "No negatives allowed: -2, -5"
end

end