简体   繁体   中英

Ruby remove blank lines from a file which include spaces

I am trying to remove blank lines from a file.

My current code is:

 def remove_blank_lines_from_file(file)
   File.write(file, File.read(file).gsub(/^$\n/, '')) 
 end

The above code removes only the empty lines, but I also want to remove the lines which include spaces.

How could I do it?

Since you nevertheless load the whole file into memory, this might be easier to read:

File.write(file, File.readlines(file).reject { |s| s.strip.empty? }.join)

Just remove those lines, containing the spaces only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM