Reputation: 35
I want to get the number of occurrences of a substring in a text.
fullText = 'aa_bb_cc_dd_eeeee_ff'
substr = 'ee'
I want to count how many times ee
matches aa_bb_cc_dd_eeeee_ff
, and the result should be 4
.
Upvotes: 2
Views: 85
Reputation: 14051
@sawa's solution is more efficient (and general) but if you want to do it without regexes, here's another way:
'aa_bb_cc_dd_eeeee_ff'.chars.each_cons(2).inject(0) { |c, (i,j)|
c+=1 if (i == 'e' && i == j); c
}
Upvotes: 0