i have a project of a game, in it i need to impress the letter selected if the letter selected is present in the secret word, but when i try to catch the index of the select letter, like "a", in the secret word "programador, the code returns me all the index of the word "programador" not only the index where the letter "a" is present.
palavra_secreta = "programador"
letra_procurada = "a"
total_encontrado = palavra_secreta.count letra_procurada
palavra_secreta_array = palavra_secreta.split("")
puts palavra_secreta_array.each_with_index.select { |letra_procurada, index|
total_encontrado >= 1
}.map { |pair| pair[1] }
this code is returning me: 0 1 2 3 4 5 6 7 8 9 10
>Solution :
In your code, total_encontrado is 2, which is greater than or equal to 1. As a result, the condition you give to #select is always true, so it selects every character with its index. You then map that to just the indices.
Instead, you likely want to select only the letters that match letra_procurada.
palavra_secreta = "programador"
letra_procurada = "a"
total_encontrado = palavra_secreta.count letra_procurada
palavra_secreta_array = palavra_secreta.split("")
puts palavra_secreta_array.each_with_index.select { |letra, index|
letra_procurada == letra
}.map { |pair| pair[1] }
You could also use #filter_map (Ruby 2.7 and later) to simplify this.
palavra_secreta = "programador"
letra_procurada = "a"
total_encontrado = palavra_secreta.count letra_procurada
palavra_secreta_array = palavra_secreta.split("")
puts palavra_secreta_array.each_with_index.filter_map { |letra, index|
index if letra_procurada == letra
}