Project

General

Profile

Actions

Feature #13890

open

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

Added by duerst (Martin Dürst) over 6 years ago. Updated about 1 year ago.

Status:
Open
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.


Related issues 1 (0 open1 closed)

Related to Ruby master - Feature #12698: Method to delete a substring by regex matchFeedbackActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like1Like0Like0Like0