Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to determine is csv with header or not in rails

Writing an application that accept only csv file with header. So trying to detect is csv file have header or not. Is there any things to do that.

like image 761
Bagi Avatar asked Oct 23 '25 18:10

Bagi


1 Answers

I put some sample data in my test.text file :

name,age,location
Ram,12,UK
Jadu,11,USA

And the code I wrote to check if the header is present or not :-

#!/usr/bin/env ruby

require 'csv'

csv = CSV.open("#{__dir__}/test.txt", :col_sep => ",", :headers => true )
p csv.read.headers
# >> ["name", "age", "location"]

Now this array you have to check, if it matches with your headers values. If it matched, then you can tell, yes header is applied.This code is written exactly on the same base as @tadman said :

here's no standard way of defining headers in a CSV file, but convention dictates that the first line, and only the first line, is headers. People are free to do whatever they want and, in the process, make your life as a developer absolutely miserable.

To know what are these options mean :col_sep, :headers checkout the documentation of CSV::new.

like image 159
Arup Rakshit Avatar answered Oct 26 '25 08:10

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!