在 Ruby 中查找字符串中的 # 匹配项

我正在寻找 Ruby 方法(1.9...) ,它可以帮助我找到字符串中一个字符的出现次数。我在寻找所有的事件,不仅仅是第一次。

比如“梅兰妮是个菜鸟” 字母“ a”有两处出现。 我可以用什么 Ruby 方法来找到它?

我一直在使用 Ruby-doc.org作为参考和 String: class中的 scan方法引起了我的注意。措辞对我来说有点难以理解,所以我并没有真正掌握 scan的概念。

编辑: 我能够解决这个使用 scan.我在指南中分享了一些解决方案对我如何实现它。

95788 次浏览

This link from a question asked previously should help scanning 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"]

If you just want the number of a's:

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

Docs for more details.

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 guide I created after I figured it out.