0

I used this method:

matchers = {'-\n' => '', '\n' => ' ', '&' => ''}
text.gsub(/-\n|\n|&/) { |match| matchers[match] }

And gsub substituted '\n' with '', not ' '. As there is a difference between single and double quotes regarding escape characters, I thought this will do something:

matchers = {"-\n" => '', "\n" => ' ', '&' => ''}

This in fact gave me the desired output, but I can't figure out why. It seems like '\n' was still removed, as there were no newlines upon puts, but it wasn't substituted. I would be grateful for an explanation.

sawa
  • 165,429
  • 45
  • 277
  • 381
cdDC
  • 21
  • 3
  • What do you mean by "the desired output"? – sawa Mar 03 '18 at 05:18
  • 1
    What is the text? What `\n` is replaced into depends on the context, given your regex. – sawa Mar 03 '18 at 05:22
  • Indeed @sawa is right. In Ruby double quotes interpret the string, aka string interpolation. "\n" is interpreted as the linefeed character. So it matters how you created the 'text' string, via single or double quotes. – Axe Mar 04 '18 at 16:06
  • See also [double vs single quotes](https://stackoverflow.com/questions/6395288/double-vs-single-quotes). – Axe Mar 04 '18 at 18:02

1 Answers1

-2

In Ruby, the string literal "\n" contains one linefeed character. But '\n' contains a literal \ and a literal n character.

As a style guideline, which nobody in Ruby follows except me and those who I taught, always prefer single 'quotes', unless you need the special abilities of double "quotes", such as your experiment.

Phlip
  • 5,253
  • 5
  • 32
  • 48
  • 2
    Here's a simple proof: `'\n' #=> "\\n"`, `"\n" #=> "\n"` or `'\n'.size #=> 2`, `"\\n".size #=> 1`. You are incorrect that no one else follows the *Ruby style guilde*. There is at least one other who does (mostly). – Cary Swoveland Mar 02 '18 at 20:54
  • 1
    The style guide is [here](https://github.com/github/rubocop-github/blob/master/STYLEGUIDE.md), (There may be others.) Worth a read. – Cary Swoveland Mar 03 '18 at 01:56
  • I dislike elements of this style guide. Good thing it has no quasi-legal status the way Python's PEP does. I dislike my editor, RubyMine, slavishly nagging about some violations of its style guide when there's a technical reason to break a guideline. And the rule "prefer single quotes" has a technical reason; it's following the general programming rule that the simplest, weakest expression wins. – Phlip Mar 03 '18 at 03:09
  • I think the OP already knows what you wrote in your first paragraph. I don't think this answer adds anything that the OP was expecting. – sawa Mar 03 '18 at 05:23