Ruby: How to count the number of times a string appears in another string? -


i'm trying count number of times string appears in string.

i know can count number of times letter appears in string:

string = "aabbccddbb" string.count('a') => 2 

but if search how many times 'aa' appears in string, two.

string.count('aa') => 2 

i don't understand this. put value in quotation marks, i'm searching number of times exact string appears, not letters.

here couple of ways count numbers of times given substring appears in string (the first being preference). note (as confirmed op) substring 'aa' appears twice in string 'aaa', , therefore 5 times in:

string="aaabbccaaaaddbb" 

#1

use string#scan regex contains positive lookahead looks substring:

def count_em(string, substring)   string.scan(/(?=#{substring})/).count end  count_em(string,"aa")  #=> 5 

note:

"aaabbccaaaaddbb".scan(/(?=aa)/)   #=> ["", "", "", "", ""] 

a positive lookbehind produces same result:

"aaabbccaaaaddbb".scan(/(?<=aa)/)   #=> ["", "", "", "", ""] 

#2

convert array, apply enumerable#each_cons, join , count:

def count_em(string, substring)   string.each_char.each_cons(substring.size).map(&:join).count(substring) end  count_em(string,"aa")   #=> 5 

we have:

enum0 = "aaabbccaaaaddbb".each_char   #=> #<enumerator: "aaabbccaaaaddbb":each_char> 

we can see elements generated enumerator converting array:

enum0.to_a   #=> ["a", "a", "a", "b", "b", "c", "c", "a", "a", "a",   #    "a", "d", "d", "b", "b"]  enum1 = enum0.each_cons("aa".size)   #=> #<enumerator: #<enumerator: "aaabbccaaaaddbb":each_char>:each_cons(2)>  

convert enum1 array see values enumerator pass on map:

enum1.to_a   #=> [["a", "a"], ["a", "a"], ["a", "b"], ["b", "b"], ["b", "c"],   #    ["c", "c"], ["c", "a"], ["a", "a"], ["a", "a"], ["a", "a"],    #    ["a", "d"], ["d", "d"], ["d", "b"], ["b", "b"]]  c = enum1.map(&:join)   #=> ["aa", "aa", "ab", "bb", "bc", "cc", "ca",   #    "aa", "aa", "aa", "ad", "dd", "db", "bb"] c.count("aa")   #=> 5 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -