정규식 패턴으로이 문제를 해결하려고합니다.이 솔루션과 함께 테스트를 통과하더라도 배열 내에 ["1", "2"]
만 있어야합니다. 이 작업을 수행하는 더 좋은 방법이 있습니까?Ruby : 구분 기호를 Regex와 일치 시키십시오
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 "'에 대한 예상 출력은 무엇입니까? –