Forum: Ruby Counting pairs of newline characters in a string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2adbbe58bd5008a7ba6180de2414cd91?d=identicon&s=25 celldee (Guest)
on 2007-04-15 01:47
(Received via mailing list)
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
http://rotsog.wordpress.com
77f306388bb6ae00ac0b0401e27cdc99?d=identicon&s=25 Chad Fowler (Guest)
on 2007-04-15 02:01
(Received via mailing list)
On 4/14/07, celldee <celldee@gmail.com> 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
2adbbe58bd5008a7ba6180de2414cd91?d=identicon&s=25 celldee (Guest)
on 2007-04-15 02:36
(Received via mailing list)
Thanks Chad, works a treat.
This topic is locked and can not be replied to.