-2

I have been recommended the following line of code to use on a text file:

arr = str.split(/\n{2,}/).map { |s| s.split(/\n/) }

Am trying to understand how the:

(/\n{2,}/)

Part is working and exactly what it does.

Ilya
  • 12,629
  • 4
  • 33
  • 48
Stoob
  • 121
  • 1
  • 9
  • 1
    `\n{2,}` means match two or more newline characters. Sometimes you will see this written `\n\n+`. – Cary Swoveland Apr 19 '16 at 06:57
  • In other words, in this case, the curly braces are part of Ruby's regular expression syntax and have nothing to do with Ruby's usual uses of curly braces, which are: 1) to mark the beginning and end of a code block, and 2) to enclose a hash. – Keith Bennett Apr 19 '16 at 09:39

1 Answers1

5

The leading and trailing / mark the beginning and the end of a regular expression. \n will match any single newline. {2,} after a symbol (in this case \n) will match any occurrence of the symbol repeated two or more times, in this case two or more consecutive newlines. Had it been \n{3,6}, it would match any consecutive newlines repeated between 3 and 6 times.

sawa
  • 156,411
  • 36
  • 254
  • 350
MicSokoli
  • 811
  • 8
  • 11