7

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.

2 Answers 2

30

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

File.foreach('test1.rb') do |line| send line.chomp end 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Mladen, it works. And thanks Greg, that's an extra lesson
5

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 

1 Comment

be warned: strip is not the same as removing exactly the last line break, it also strips white spaces at the beginning of a line. So if you're like me, trying to read a tsv file(which could start with a bunch of tabs), chomp is the way to go as @mladen answered

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.