Lennie
Lennie

Reputation: 10845

The string count() method

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?

Upvotes: 8

Views: 6718

Answers (2)

Sarah Mei
Sarah Mei

Reputation: 18484

If you give count more than one argument, it only counts letters that are in all the arguments. So in your first example, it's only counting o. In your second example, it's only counting e.

Upvotes: 0

Gordon Wilson
Gordon Wilson

Reputation: 26384

"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.

Upvotes: 18

Related Questions