Read file and search word

Asked

Viewed 743 times

1

I’m riding a script that will open a text file, play the words in a array, and then capture the word content, so far so good I can get the word content, but I need to go through all the array and if I have the word repeated, I need to keep all the contents of that word.

Test file.txt:

a;b;c;a;d;

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

He’s only capturing the first position, but I have the letter a repeated, I need to keep all the indexes referring to a.

Does anyone have any idea what I can do?

2 answers

2


You can use the methods 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 on the array with Integer#times according to the number of elements, and 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 so:

#!/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

-1

If you want to find out which letter repeats, you can do so:

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

Upshot:

=> {"a"=>3}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.