Edit each line in a file in Ruby -


I am trying to find an easy way to edit each line in a file, and I have a problem How do I understand to use the file class to do this?

The line I want to edit is that there are several hundred rows in each line with commas separated values, I am only interested in the first value in each line, and I first assume all values I tried to delete the following: Try

  File.open ('filename.txt', 'r +'). File | File.each_line {| Line | Line = line. Split (",") [0]} file.write file.close end   

that does not work because the File.write method is required The content is to be written in the form of logic.

Can someone add me how can I get the desired effect?

Using one of the better solutions (and the most secure) to create a temporary file and complete it It needs to be moved to the original location:

  is required 'fileutils' requires 'tempfile' t_file = Tempfile.new ('filename_temp.txt') File.open (" Filename.txt ", 'r') do. F | F.each_line {| Line | T_file.puts line.split (",") [0] .to_s} end t_file.close FileUtils.mv (t_file.path, "filename.txt")    

Comments