Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The string count() method

Tags:

ruby

Busy learning Ruby... the documentation have an example:

"hello world".count("lo", "o") that return 2 how does that return 2?

In my example I've: puts "Lennie".count("Le", "ie") that return 2.

How does count work in this regard?

like image 860
Lennie Avatar asked Mar 01 '09 21:03

Lennie


Video Answer


1 Answers

"hello world".count("lo") returns five. It has matched the third, fourth, fifth, eighth, and tenth characters. Lets call this set one.

"hello world".count("o") returns two. It has matched the fifth and eighth characters. Lets call this set two.

"hello world".count("lo", "o") counts the intersection of sets one and two.

The intersection is a third set containing all of the elements of set two that are also in set one. In our example, both sets one and two contain the fifth and eighth characters from the string. That's two characters total. So, count returns two.

like image 199
Gordon Wilson Avatar answered Sep 23 '22 17:09

Gordon Wilson