Ruby write all puts lines in file?

I have a file

ppp.txt

mmm;2;nsfnjd;pet;
sadjjasjnsd;6;gdhjsd;pet;
gsduhdssdj;3;gsdhjhjsd;dog;

      

I need to write

nsfnjd
gsdhjhjsd

      

I am using this code but I only print the last line "gsdhjhjsd" I don't know what is doing wrong

 File.open("ppp.txt", "r")  do |fi|
  fi.readlines.each do |line|
    parts = line.chomp.split(';')


    if parts[1].to_i < 4

 puts parts[2]
 File.open("testxx.txt", "w+") do |f|
  f. puts parts[2]
end

    end

  end
end

      

Please help me

+3


source to share


2 answers


Open the file using append mode, 'a +' instead of write mode 'w +', which overwrites the file as the open command is called inside the loop.



Or open the write file before looping through the lines of the read file.

+1


source


open file descriptor outside of loop

fo = File.open("testxx.txt","w+")
File.open("ppp.txt", "r")  do |fi|
  fi.readlines.each do |line|
    parts = line.chomp.split(';')
    fo.puts parts[2] if parts[1].to_i < 4
  end
end
fo.close()

      



NOTE. You must explicitly close fo

but open the file using a block; ruby automatically closes the file ( fi

case).

+1


source







All Articles