Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby each_line reads line break too?

Tags:

ruby

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.

like image 762
Wenyang Avatar asked Dec 16 '10 17:12

Wenyang


People also ask

How do you read a line by line in Ruby?

Overview. The IO instance is the basis for all input and output operations in Ruby. Using this instance, we can read a file and get its contents line by line using the foreach() method. This method takes the name of the file, and then a block which gives us access to each line of the contents of the file.

How do you break a line in Ruby?

\r\n should probably do the trick.

How can you read an entire file and get each line in Ruby?

Use File#readlines to Read Lines of a File in Ruby File#readlines takes a filename to read and returns an array of lines. Newline character \n may be included in each line. We must be cautious when working with a large file, File#readlines will read all lines at once and load them into memory.

How do you make a new line in Ruby?

\n is the newline character. It prints a new line.


1 Answers

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

File.foreach('test1.rb') do |line|
  send line.chomp
end
like image 151
Mladen Jablanović Avatar answered Sep 22 '22 11:09

Mladen Jablanović