Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Doing a simple count

1 view
Skip to first unread message

Peter Bailey

unread,
Mar 16, 2011, 8:41:25 AM3/16/11
to
Hello,
I've got some enormous RTF files and I need to get a count of the number
of footnotes in them. So, I'm trying this:

Dir.chdir("T:/rtf")
file_contents = File.read("1.rtf")
count = file_contents.count "\footnote"
puts count

I'm getting an enormous value (115683) in the hundreds of thousands.
And, with my text editor, I know that there are only hundreds (582). Can
someone please explain why this is happening?

Thanks,
Peter

--
Posted via http://www.ruby-forum.com/.

Stefano Crocco

unread,
Mar 16, 2011, 8:54:54 AM3/16/11
to

String#count doesn't work the way you expect. It doesn't count the number of
occurrences of the argument in the receiver, but the number of occurrences of
any one of the characters making up the argument. For example:

"ab ac ad".count "ab"
=> 4

"ab ac ad".count "ae"
=> 3

In the first examples, 4 is obtained by summing the 3 occurrences of 'a' and
the one occurrence of 'b'. In the second, 'e' is never found, so only the
three occurrences of 'a' are returned. For other examples, see the ri
documentation for String#count

To obtain what you want, you can use

file_contents.scan(/\\footnote/).count

I don't know if there's a better way.

I hope this helps

Stefano

0 new messages