Reputation: 57
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
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:
-
means a range\
escapes the other two and is ignoredUpvotes: 9