我試圖用正則表達式模式來解決這個問題,即使我的測試通過了這個解決方案,我想分割成在陣列中只有["1", "2"]
。有沒有更好的方法來做到這一點?紅寶石:與正則表達式匹配的分隔符
IRB測試:
s = "//;\n1;2" # when given a delimiter of ';'
s2 = "1,2,3" # should read between commas
s3 = "//+\n2+2" # should read between delimiter of '+'
s.split(/[,\n]|[^0-9]/)
=> ["", "", "", "", "1", "2"]
生產:
module StringCalculator
def self.add(input)
solution = input.scan(/\d+/).map(&:to_i).reduce(0, :+)
input.end_with?("\n") ? nil : solution
end
end
測試:
context 'when given a newline delimiter' do
it 'should read between numbers' do
expect(StringCalculator.add("1\n2,3")).to eq(6)
end
it 'should not end in a newline' do
expect(StringCalculator.add("1,\n")).to be_nil
end
end
context 'when given different delimiter' do
it 'should support that delimiter' do
expect(StringCalculator.add("//;\n1;2")).to eq(3)
end
end
時,你會改變你的帖子,寫一個字**編輯**,並把新的內容。不要刪除第一篇文章。如果你刪除的人會認爲我* STUPID *,希望你明白。 –
明白了,我已經對問題有了更多的瞭解。 @ArupRakshit – theGrayFox
「1,2,3」的預期輸出? –