steady_daddy steady_daddy - 3 years ago 160
Ruby Question

How does count method works in Ruby?

I have a hard time understanding the following code segment from the Ruby docs:

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

"hello^world".count "\\^aeiou" #=> 4
"hello-world".count "a\\-eo" #=> 4

especially this code
a.count "ej-m"
. Can anyone please explain how it works?

Answer Source

Just imagine the "pattern" strings as wrapped by [ and ] from regex syntax, that are matched against each character.

So, if we break a = "hello world" into characters:

[1] pry(main)> a = "hello world"
=> "hello world"
[2] pry(main)> a.split('')
=> ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

And convert "ej-m" to regex wrapped with [ and ] we get /[ej-m]/ - which means either 'e' or any character from 'j' to 'm'(including both):

[3] pry(main)> a.split('').select{|c| c=~ /[ej-m]/}
=> ["e", "l", "l", "l"]

We got 4 matches - which is also the result you get. Essensially a.count "ej-m" is equivalent to:

[4] pry(main)> a.split('').count{|c| c=~ /[ej-m]/}
=> 4

Multiple arguments to the method are just and between the matches:

[5] pry(main)> a.split('').count{|c| c =~ /[hello]/ and c =~ /[^l]/}
=> 4
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download