We find that
"hello world".count("ej-m") #=> 4 (_ell_____l_)
Examine the doc for String#count carefully.
Here is how count
might be implemented to deal with patterns that closely resemble the pattern "ej-m"
.
def count_letters(str, pattern)
idx = pattern[1..-2].index('-')
if idx
idx += 1
before, after = pattern[idx-1], pattern[idx+1]
pattern[idx-1..idx+1] = (before..after).to_a.join
end
str.each_char.sum { |c| pattern.include?(c) ? 1 : 0 }
end
count_letters(str, pattern) #=> 4 (_ell_____l_)
However, String#count
must also do the following.
Allow for multiple ranges in the pattern
"hello1world".count("e0-9j-mv-x") #=> 6 (_ell__1_w__l_)
If the pattern begins with the character '^'
count the number of characters that do not match the remainder of the pattern
"hello world".count("^ej-m") #=> 7 (h___o*wor_d) * = space to count
"hello^world".count("e^j-m") #=> 5 (_ell_^___l_)
"hello world".count("\^ej-m") #=> 7 (h___o*wor_d) * = space to count
Note that escaping '^'
at the beginning of the string makes no difference.
Match a hyphen
"hello-world".count("ej-m-") #=> 5 (_ell_-___l_)
"hello-world".count("-ej-m") #=> 5 (_ell_-___l_)
"hello-world".count("ej\-m") #=> 4 (_ell____l_)
Note that escaping a hyphen that is not the first or last character of the pattern makes no difference.
Match a backslash
'hello\world'.count("ej-m\\") #=> 5 (_ell_\___l_)
'hello\world'.count("\\ej-m") #=> 4 (_ell____l_)
Note that a backslash at the beginning of a string is disregarded.
Some of the above results (Ruby v2.4) do not seem to be consistent with the documentation.