简体   繁体   中英

Ruby: Escaping String Characters

After realizing why my test failed, I would like to retain the idea of using only single-quotes when I'm not interpolating something. In this case however, because of that, my test fails. Is there a way to not escape the string '1\\n,2,3' without having to convert all of my tests to using double-quotes?

My code is as follows:

Spec:

describe '#add' do
  before(:each) do
    @calc = StringCalculator.new
  end

  context 'when given a delimiter' do
    it 'should support newlines' do
      expect(@calc.add('1\n2,3')).to eq(6)
    end
  end
end

Calc.rb:

class StringCalculator
  attr_reader :numbers

  def initialize(numbers = '')
    @numbers = numbers
  end

  def add(expression)
    @numbers.concat(expression)
    @numbers.gsub!(/\n/, ',')
    @numbers.empty? ? 0 : result
  end

  def result
    @numbers.split(',').map(&:to_i).reduce(:+)
  end
end

Well, if you really , really want to avoid using double-quotes you could insert a literal newline character between the single quotes:

  expect(@calc.add('1
2,3')).to eq(6)

In my opinion that's really ugly though. If you want to use the features unique to double-quotes (IE the escaped newline character) then why not just use double quotes? It's not like they're evil or anything, nothing to be afraid of:

expect(@calc.add("1\n2,3")).to eq(6)

Also, you don't have to "convert all of your tests to using double-quotes" if you don't want to. Personally, my rule of thumb is to use single quotes when you can, and double quotes wherever you need them. Use the right tool for the job.


Here's a quote from the Ruby style guide on GitHub which seems to agree with me:

  • Prefer single-quoted strings when you don't need string interpolation or special symbols such as \\t , \\n , ' , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM