Ruby:匹配分隔符

时间:2014-02-15 02:50:55

标签: ruby regex

我想写一个正则表达式模式来查找字符串中的分隔符,例如:'//;\n1;2'其中字符;用作给定字符串的分隔符。我正在尝试解决一个常见的编码kata问题,所以我不一定想要代码中的答案,而是想知道我如何用正则表达式完成这个。此分隔符可能会发生变化,可能是任何字符。有任何想法吗?这是我到目前为止在我的生产文件中写的内容。

class StringCalculator
  def add(numbers)
    return 0 if numbers.empty?
    return nil if numbers.end_with?('\n')
    numbers.tr!('\n', ',')
    numbers.split(',').map(&:to_i).reduce(:+)
  end
end

规格:

context 'when passed different delimiters' do
  it 'should support semicolons' do
    expect(@calculator.add('//;\n1;2')).to eq(3)
  end

  it 'should support percents' do
    expect(@calculator.add('//%\n1%5')).to eq(6)
  end
end

0 个答案:

没有答案