Counting Strings Within Strings – scan
This is the first post in my Not Obvious To Me (N.O.T.M) section. Here lie examples of my intuitive (or just plain misguided) use of Ruby that have not yielded the results that I expected.
The problem was how to count the occurrences of pairs of newline characters in a given string. I was looking for newline but this case holds good for other repeating characters. Seemed to me that the String.count method should be used. Nice try brother, but how do I break this gently – No! What happens in irb is this:-
irb(main):001:0> str = “Rita, Bob
irb(main):002:0″
irb(main):003:0″ and Sue too”
=> “Rita, Bob\n\nand Sue too”
irb(main):004:0> str.count(“\n\n”)
=> 2
As you can see the result is 2, even though I entered a pair of newline characters. What I should have used was the String.scan method like this:-
irb(main):001:0> str = “Rita, Bob
irb(main):002:0″
irb(main):003:0″ and Sue too”
=> “Rita, Bob\n\nand Sue too”
irb(main):004:0> str.scan(/\n\n/).size
=> 1
Voila, the answer is 1, just as required. Notice that the result from the scan method is an array, each element containing an occurrence of your search string; consequently the size or length method is invoked to get the number.
This solution was provided by Chad Fowler (not sure whether this is the Ruby-famous Chad) via the ruby-talk-google group. Much obliged.