Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple Index Array – Ruby

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading