How to read lines of a file in Ruby

后端 未结 8 1304
轮回少年
轮回少年 2020-12-02 04:16

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\'         


        
8条回答
  •  借酒劲吻你
    2020-12-02 04:55

    It is because of the endlines in each lines. Use the chomp method in ruby to delete the endline '\n' or 'r' at the end.

    line_num=0
    File.open('xxx.txt').each do |line|
      print "#{line_num += 1} #{line.chomp}"
    end
    

提交回复
热议问题