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
How can I test if a letter (stored in a variable) is contained in a word? ex:
palavra = "palavra"
escolha = "a"
The word has 3 letters "a" in the word .... or
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 .
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
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")