Melanie Shebel Melanie Shebel - 1 year ago 55
Ruby Question

Finding occurrences of a character in a string with Ruby

I'm looking for the Ruby method (1.9...) that can help me find the number of occurrences of a character in a string. I'm looking for all occurrences, not just the first one.

For example: "Melanie is a noob"
There are two occurrences of the letter a.
What would be the Ruby method I could use in order to find this?

I've been using as a reference and the scan method in the String class, in particular, caught my eye. However, the wording is a bit difficult for me, so I don't really grasp the concept of scan.

Answer Source

If you just want the number of a's:

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