Read file and search word

1
I'm putting together a script that will open a text file, play the words in a array , and then capture the index of the word, so alright I can get the word index , but I need to go through all array and if I have the word repeated, I need to save all indexes of that word.

Test.txt file:

  

a; b; c; a; d; a

Code:

file = File.open('teste.txt')
#fazendo um For Linha a Linha
file.each_line do |line|
        #Separando as palavras e convertendo para string      

        values = line.split(';').to_s()
        #capturando o index da palavra que seja igual a 'a'
        #idExc = Array[]
        idExc = values.index(/a/)

        puts values[idExc]

end

It is only capturing the first position, but I have the letter a repeated, I need to save all indexes referring to a .

Anyone know how to do this?

    
asked by anonymous 22.09.2016 / 22:54

2 answers

2

You can use Array#each_index and Array#select :

values = [ "a", "b", "c", "a", "d" ]

p values.each_index.select { |i| values[i] == 'a' } #=> [0, 3]

Another alternative is to iterate over array with Integer#times based on the number of elements, and with Array#select you do the filtering:

p values.size.times.select { |i| values[i] == 'a' } #=> [0, 3]

See DEMO

In your case, you can do this:

#!/usr/bin/env ruby

File.open('teste.txt').each_line do |line|
   line = line.strip
   values = line.split(';')

   p values.size.times.select { |i| values[i] == 'a' }              
end
    
23.09.2016 / 01:19
-1

If you want to find out which letter you repeat, you can do it like this:

File.read("/tmp/teste.txt").chomp. split(/;/). reduce(Hash.new(0)) { |m, i| m[i] += 1; m }. select { |k, v| v > 1 }

Result:

=> {"a"=>3}

    
29.03.2017 / 00:13