Finding # occurrences of a character in a string in Ruby

前端 未结 3 1033
情书的邮戳
情书的邮戳 2021-01-30 15:28

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.

3条回答
  •  既然无缘
    2021-01-30 16:01

    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.

提交回复
热议问题