How to find a letter in a string?

1

How can I test if a letter (stored in a variable) is contained in a word? ex:

palavra = "palavra"
escolha = "a"

output

  

The word has 3 letters "a" in the word .... or

    
asked by anonymous 01.03.2017 / 13:08

3 answers

3

I'm not a big fan of RegEx, but Ruby encourages not having a very simple solution to this and having specific syntax for regular expressions, so I find the most appropriate.

palavra = "palavra"
escolha = "a"
contagem = palavra.scan(/(?=#{escolha})/).count
puts "A palavra tem #{contagem} letras 'a' na palavra"

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
01.03.2017 / 13:20
2

A fairly readable format would be to use the character array that any String offers joined with a count :

lookup_char = 'a'
'abcd abc ab a'.chars.count {|c| c == lookup_char} # => 4
    
05.03.2017 / 05:32
1

If you just want to know if you include the lyrics:

"palavra".include?("a")

If you want the number of times it appears:

"palavra".count("a")

    
28.03.2017 / 23:49