# Counting pairs of newline characters in a string

**URL:** <https://www.ruby-forum.com/t/counting-pairs-of-newline-characters-in-a-string/92036>\
**Category:** Ruby\
**Created:** [April 15, 2007, 1:47am UTC](https://www.ruby-forum.com/t/counting-pairs-of-newline-characters-in-a-string/92036 "2007-04-15T01:47:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![celldee](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/76d3ee/32.png) [@celldee](https://www.ruby-forum.com/u/celldee)\
**Post date:** [April 15, 2007, 1:47am UTC](https://www.ruby-forum.com/t/counting-pairs-of-newline-characters-in-a-string/92036/1 "2007-04-15T01:47:08Z")

</div>

I have a string that is text read in from a file. Within it there are  
pairs of newline characters and I want to count how many there are.  
Here is an irb example:-

irb(main):001:0\> str = “bob  
irb(main):002:0”  
irb(main):003:0" and Jane"  
=\> “bob\n\nand Jane”  
irb(main):004:0\> str.count(“\n\n”)  
=\> 2

Each newline character is counted separately so I get the number 2  
returned instead of the number 1 which is what I require.  
Is there a way for me to count pairs of newline characters with a  
simple function?

Regards,

Chris

> **[Ruby On The Shoulders Of Giants](https://rotsog.wordpress.com)**
>
> Code Red

---

<div class="post-metadata">

**Author:** ![celldee](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/76d3ee/32.png) [@celldee](https://www.ruby-forum.com/u/celldee)\
**Post date:** [April 15, 2007, 2:36am UTC](https://www.ruby-forum.com/t/counting-pairs-of-newline-characters-in-a-string/92036/2 "2007-04-15T02:36:10Z")

</div>

Thanks Chad, works a treat.

---

<div class="post-metadata">

**Author:** ![celldee](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/76d3ee/32.png) [@celldee](https://www.ruby-forum.com/u/celldee)\
**Post date:** [April 15, 2007, 2:01am UTC](https://www.ruby-forum.com/t/counting-pairs-of-newline-characters-in-a-string/92036/3 "2007-04-15T02:01:09Z")

</div>

On 4/14/07, celldee [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Each newline character is counted separately so I get the number 2  
> returned instead of the number 1 which is what I require.  
> Is there a way for me to count pairs of newline characters with a  
> simple function?

Hi. One way is: str.scan(/\n\n/).size

Chad
