Wenyang
Wenyang

Reputation: 93

ruby each_line reads line break too?

I'm trying to read data from a text file and join it with a post string. When there's only one line in the file, it works fine. But with 2 lines, my request is failed. Is each_line reading the line break? How can I correct it?

File.open('sfzh.txt','r'){|f|
f.each_line{|row|
    send(row)
}

I did bypass this issue with split and extra delimiter. But it just looks ugly.

Upvotes: 7

Views: 13943

Answers (2)

David G
David G

Reputation: 5784

Another way is to map strip onto each line as it is returned. To read a file line-by-line, stripping whitespace and do something with each line you can do the following:

File.open("path to file").readlines.map(&:strip).each do |line|
   (do something with line)
end

Upvotes: 5

Mladen Jablanović
Mladen Jablanović

Reputation: 44080

Yes, each_line includes line breaks. But you can strip them easily using chomp:

File.foreach('test1.rb') do |line|
  send line.chomp
end

Upvotes: 30

Related Questions