AidanofVT
AidanofVT

Reputation: 57

Would someone help me understand the Ruby manual's example of str.counts?

In every other example I see, str.count is quite simple. It just counts the instances of the parameter in the string. But the example of the method given in the Ruby manual seems incomprehensible (see below). It doesn't even use parenthesis! Could anyone help elucidate this for me?

a = "hello world"
a.count "lo"            »   5
a.count "lo", "o"       »   2
a.count "hello", "^l"   »   4
a.count "ej-m"          »   4

Upvotes: 3

Views: 83

Answers (1)

Jay Dorsey
Jay Dorsey

Reputation: 3662

It's counting the number of occurences of the letters you passed in as an argument

a.count("lo") # 5, counts [l, o]
hello world
  ***  * *

# counts all [h, e, o], but not "l" because of the caret
a.count "hello", "^l" # 4
hello world
**  *  *

a.count "ej-m" # counts e, and the characters in range j, k, l, m
hello world
 ***     *

There's a couple special characters:

  • caret ^ is negated.
  • The - means a range
  • The \ escapes the other two and is ignored

Upvotes: 9

Related Questions