Allow a regexp as an argument to 'count', to count more interesting things than single characters
Currently, String#count only accepts strings, and counts all the characters in the string.
However, I have repeatedly met the situation where I wanted to count more interesting things in strings.
These 'interesting things' can easily be expressed with regular expressions.
Here is a quick-and-dirty Ruby-level implementation:
class String alias old_count count def count (what) case what when String old_count what when Regexp pos = -1 count = 0 count += 1 while pos = index(what, pos+1) count end end end
Please note that the implementation counts overlapping occurrences; maybe there is room for an option like
Updated by duerst (Martin Dürst) over 3 years ago
Python allows to count strings, as follows:
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of
sub in the range
[start, end]. Optional arguments
end are interpreted as in slice notation.