Finding # occurrences of a character in a string in Ruby Finding # occurrences of a character in a string in Ruby ruby ruby

Finding # occurrences of a character in a string in Ruby


If you just want the number of a's:

puts "Melanie is a noob".count('a')  #=> 2

Docs for more details.


This link from a question asked previously should helpscanning a string in Ruby

scan returns all the occurrences of a string in a string as an array, so

"Melanie is a noob".scan(/a/)

will return

["a","a"]


I was able to solve this by passing a string through scan as shown in another answer.

For example:

string = 'This is an example'puts string.count('e')

Outputs:

2

I was also able to pull the occurrences by using scan and passing a sting through instead of regex which varies slightly from another answer but was helpful in order to avoid regex.

string = 'This is an example'puts string.scan('e')

Outputs:

['e','e']

I explored these methods further in a small video guide I created after I figured it out.