[ruby-core:111366] [Ruby master Feature#13890] Allow a regexp as an argument to 'count', to count more interesting things than single characters

Issue #13890 has been updated by shan (Shannon Skipper). I'd love to have this feature. A `str.count(regexp)` is something I see folk trying fairly often. A `str.count(regexp)` also avoids the intermediary Array of `str.scan(regexp).size` or the back bending with `str.enum_for(:scan, regexp).count`. ---------------------------------------- Feature #13890: Allow a regexp as an argument to 'count', to count more interesting things than single characters https://bugs.ruby-lang.org/issues/13890#change-100741 * Author: duerst (Martin Dürst) * Status: Open * Priority: Normal ---------------------------------------- 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: ````Ruby 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 `overlap: :no`. -- https://bugs.ruby-lang.org/
participants (1)
-
shan (Shannon Skipper)