Skip to content
instance method

String#count

(::String::selector selector_0, *::String::selector more_selectors) -> ::Integer
count(*selectors) → integer

Returns the total number of characters in self that are specified by the given selectors.

For one 1-character selector, returns the count of instances of that character:

Example
s = 'abracadabra'
s.count('a') # => 5
s.count('b') # => 2
s.count('x') # => 0
s.count('')  # => 0

s = 'тест'
s.count('т')  # => 2
s.count('е')  # => 1

s = 'よろしくお願いします'
s.count('よ')  # => 1
s.count('し')  # => 2

For one multi-character selector, returns the count of instances for all specified characters:

Example
s = 'abracadabra'
s.count('ab')     # => 7
s.count('abc')    # => 8
s.count('abcd')   # => 9
s.count('abcdr')  # => 11
s.count('abcdrx') # => 11

Order and repetition do not matter:

Example
s.count('ba')   == s.count('ab') # => true
s.count('baab') == s.count('ab') # => true

For multiple selectors, forms a single selector that is the intersection of characters in all selectors and returns the count of instances for that selector:

Example
s = 'abcdefg'
s.count('abcde', 'dcbfg') == s.count('bcd') # => true
s.count('abc', 'def')     == s.count('')    # => true

In a character selector, three characters get special treatment:

  • A caret ('^') functions as a negation operator for the immediately following characters:

    Example
    s = 'abracadabra'
    s.count('^bc') # => 8  # Count of all except 'b' and 'c'.
    
  • A hyphen ('-') between two other characters defines a range of characters:

    Example
    s = 'abracadabra'
    s.count('a-c') # => 8  # Count of all 'a', 'b', and 'c'.
    
  • A backslash ('\') acts as an escape for a caret, a hyphen, or another backslash:

    Example
    s = 'abracadabra'
    s.count('\^bc')           # => 3  # Count of '^', 'b', and 'c'.
    s.count('a\-c')           # => 6  # Count of 'a', '-', and 'c'.
    'foo\bar\baz'.count('\\') # => 2  # Count of '\'.
    

These usages may be mixed:

Example
s = 'abracadabra'
s.count('a-cq-t') # => 10  # Multiple ranges.
s.count('ac-d')   # => 7   # Range mixed with plain characters.
s.count('^a-c')   # => 3   # Range mixed with negation.

For multiple selectors, all forms may be used, including negations, ranges, and escapes.

Example
s = 'abracadabra'
s.count('^abc', '^def') == s.count('^abcdef') # => true
s.count('a-e', 'c-g')   == s.count('cde')     # => true
s.count('^abc', 'c-g')  == s.count('defg')    # => true

Related: see Querying.

See also #concat #crypt #codepoints #dedup also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0