Eugene Matveyev
Eugene Matveyev

Reputation: 161

How does count work in Ruby

I understand how the method "count" works, from The string count() method.

But I can't understand how it's counting words (rather than letter) in arrays:

def find_frequency(sentence, word)
  sentence.downcase.split.count(word.downcase)
end

find_frequency("to be or not to be", "to") # => 2
  # same as ["to", "be", "or", "not", "to", "be"].count("to")
"hello world".count("lo") # => 5

If "hello world".count("lo") returns five, why doesn't find_frequency("to be or not to be", "to") return seven (t, o, o, o, t, t, o)?

Upvotes: 0

Views: 838

Answers (1)

toch
toch

Reputation: 3945

According the documentation, count(p1) for Array

Returns the number of elements. If an argument is given, counts the number of elements which equals to obj. If a block is given, counts the number of elements yielding a true value.

In your case, sentence.downcase.split gives you ["to", "be", "or", "not", "to", "be"]. Here, you have two array elements equaling "to", that's why you obtain 2.

From the documentation of String, count(*args)

Each other_str parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any other_str that starts with a caret (^) is negated. The sequence c1–c2 means all characters between c1 and c2.

If we put aside the negation case, given a String parameter p, call count on a String x returns the number of characters in x matching one of the characters of p.

In your case, you have "llool" in "hello world" matching "lo", i.e. 5

Upvotes: 2

Related Questions