String#count options

Solution 1:

This is one of the dorkiest ruby methods, and pretty lousy documentation to boot. Threw me for a loop. I ended up looking at it because it looked like it should give me the count of occurrences of a given string. Nope. Not remotely close. But here is how I ended up counting string occurrences:

s="this is a string with is thrice"
s.scan(/is/).count  # => 3

Makes me wonder why someone asked for this method, and why the documentation is so lousy. Almost like the person documenting the code really did not have a clue as to the human-understandable "business" reason for asking for this feature.

count([other_str]+) → fixnum

Each _other_str_ parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any _other_str_ that starts with a caret (^) is negated. The sequence c1–c2 means all characters between c1 and c2.

Solution 2:

If you pass more than 1 parameter to count, it will use the intersection of those strings and will use that as the search target:

a = "hello world"
a.count "lo"            #=> finds 5 instances of either "l" or "o"
a.count "lo", "o"       #=> the intersection of "lo" and "o" is "o", so it finds 2 instances
a.count "hello", "^l"   #=> the intersection of "hello" and "everything that is not "l" finds 4 instances of either "h", "e" or "o"
a.count "ej-m"          #=> finds 4 instances of "e", "j", "k", "l" or "m" (the "j-m" part)

Solution 3:

Let's break these down

a = "hello world"
  1. to count the number of occurrences of the letters l and o

    a.count "lo" #=> 5

  2. to find the intersect of lo and o (which is counting the number of occurrences of l and o and taking only the count of o from the occurrences):

    a.count "lo", "o" #=> 2

  3. to count the number of occurrences of h, e, l, l and o, then intersect with any that are not l (which produces the same outcome to finding occurrences of h, e and o)

    a.count "hello", "^l" #=> 4

  4. to count the number of occurrences of e and any letter between j and m (j, k, l and m):

    a.count "ej-m" #=> 4

Solution 4:

Each argument defines a set of characters. The intersection of those sets determines the overall set that count uses to compute a tally.

a = "hello world"

a.count "lo"            # l o       => 5
a.count "lo", "o"       # o         => 2

And ^ can be used for negation (all letters in hello, except l)

a.count "hello", "^l"   # h e o     => 4

Ranges can be defined with -:

a.count "ej-m"          # e j k l m => 4