I was trying to use the following code to read lines from a file. But when reading a file, the contents are all in one line:
line_num=0
File.open('xxx.txt').each do |line|
print "#{line_num += 1} #{line}"
end
But this file prints each line separately.
I have to use stdin, like ruby my_prog.rb < file.txt
, where I can't assume what the line-ending character is that the file uses. How can I handle it?
line_num = 0
, you could useeach.each_with_index
or possiblyeach.with_index
. – Andrew Grimm May 16 '11 at 4:15read
. – the Tin Man Aug 19 '14 at 0:09line.chomp
to handle the line endings (courtesy of @SreenivasanAC) – Yarin Feb 22 '15 at 22:14