Project

General

Profile

Feature #13890

Allow a regexp as an argument to 'count', to count more interesting things than single characters

Added by duerst (Martin Dürst) 2 months ago. Updated 2 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:82743]

Description

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 overlap: :no.

History

#1 [ruby-core:82745] Updated by Eregon (Benoit Daloze) 2 months ago

Should it behave the same as str.scan(regexp).size ?

I think the default should be no overlap, and increment the position by the length of the match.

#2 [ruby-core:82746] Updated by duerst (Martin Dürst) 2 months ago

Eregon (Benoit Daloze) wrote:

I think the default should be no overlap, and increment the position by the length of the match.

That would be fine by me, too.

Also available in: Atom PDF