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. B开发者_开发知识库ut 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.
Yes, each_line
includes line breaks. But you can strip them easily using chomp
:
File.foreach('test1.rb') do |line|
send line.chomp
end
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
精彩评论