tags:

views:

39

answers:

1

I have the following code:

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

The delete gets rid of the \n, but the result looks like this:

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

Want it to return :

line1
line2

Been fighting this problem all day. Thanks for your help

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

And now let me explain :)

  1. p expr is equivalent to puts expr.inspect, which will show the result.

  2. rstrip is a simpler way to remove the trailing newlines (and any trailing spaces).

  3. delete_if(&:empty?), which is equivalent to delete_if{|x| x.empty?} checks to see if the strings are blank, and doesn't let them through if so.

Peter