Zero Line Removal

I have the following code:

f = File.open("/log/mytext.txt")
f.each_line do |i|
i = i.delete("\n")
puts i.inspect

Removing gets rid of \ n, but the result is as follows:

"#<MatchData \"line1\">"
""
""
""
"#<MatchData \"line2\">"

Want him back:

line1
line2

Fighting this problem all day. Thank you for your help.

+1
source share
1 answer
p File.open("/log/mytext.txt").each_line.map(&:rstrip).delete_if(&:empty?)

Now let me explain :)

  • p exprequivalent puts expr.inspect, which will show the result.

  • rstrip is an easier way to remove trailing newlines (and any trailing spaces).

  • delete_if(&:empty?), which is equivalent, delete_if{|x| x.empty?}checks if the lines are not empty and do not skip them, if so.

+2
source

All Articles