Ruby CSV - get current line/row number

前端 未结 4 2048
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 05:51

I\'m trying to work out how to get the current line/row number from Ruby CSV. This is my code:

options = {:encoding => \'UTF-8\', :skip_blanks => true}         


        
4条回答
  •  感情败类
    2020-12-13 06:25

    Ruby 2.6+

    Without Headers

    CSV.foreach( "data.csv", encoding: "UTF-8" ).with_index do |row, row_number|
      puts row_number
    end
    

    With Headers

    CSV.foreach( "data.csv", encoding: "UTF-8", headers: true ).with_index( 2 ) do |row, row_number|
      puts row_number # Starts at row 2, which is the first row after the header row.
    end
    

    In Ruby 2.6, $INPUT_LINE_NUMBER no longer gives you the current line number. What's worse is that it's returning values of 2 and 1. I'm not sure what that is supposed to represent but it's certainly not the row number. Since it doesn't raise an exception, it can really bite you if you're not checking that value. I highly recommend you replace all occurrences of $INPUT_LINE_NUMBER in your code to avoid this gotcha.

提交回复
热议问题