Search code examples
rubycsvruby-on-rails-5

Rails Not Reading a Specific Column from CSV


I'm trying to read my CSV file in Rails 5.2.3 (Ruby 2.6.3) and it's not reading a specific column.

CSV file:

barcode,hardware,title,price
2900007868390,PS4,title1,300
3499550362923,PS4,title2,1800
3499550370973,Nintendo Switch,title3,5000

and so on...

Code:

csv = CSV.read('path/to/my_csv.csv', headers: true)
csv.each do |row|
  puts "#{row['barcode']}, #{row['hardware']}, #{row['title']}, #{row['price']}"
end

Result:

, PS4, title1, 300
, PS4, title2, 1800
, Nintendo Switch, title3, 5000

and so on...

As you can see above, it's not reading the barcode column for some reason.
I've managed to get the barcode value if I write row[0] instead of row['barcode'] .
Any ideas why this is happening?


Solution

  • This was because my CSV file had BOMs...
    https://en.wikipedia.org/wiki/Byte_order_mark

    The code below solved the problem:

    csv = CSV.read("resources/games/original_#{date}.csv", 'r:BOM|UTF-8', headers: true)
    

    Thank you @dimitry_n for your help!