title: how to get headers from a CSV file in ruby
body: <p>I need to validate headers in a CSV file before parsing data in it. </p>
  
  <pre><code># convert the data into an array of hashes
  CSV::Converters[:blank_to_nil] = lambda do |field|
    field &amp;&amp; field.empty? ? nil : field
  end
  csv = CSV.new(file, :headers =&gt; true, :header_converters =&gt; :symbol, :converters =&gt; [:all, :blank_to_nil])
  csv_data = csv.to_a.map {|row| row.to_hash }
  </code></pre>
  
  <p>I know I can use headers method to get the headers</p>
  
  <pre><code>    headers = csv.headers
  </code></pre>
  
  <p>But the problem with <a href="http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-i-headers" rel="noreferrer">headers method</a> is it "Returns nil if headers will not be used, true if they will but have not yet been read, or the actual headers after they have been read."</p>
  
  <p>So if I put <code>headers = csv.headers</code> above <code>csv_data = csv.to_a.map {|row| row.to_hash }</code> line <code>headers</code> is <code>true</code> and if I put it after reading data, <code>headers</code> contain headers row in an array. It imposes an order of instructions on my method which is very hard to test and is bad programming. </p>
  
  <p>Is there a way to read headers row without imposing order in this scenario? I'm using ruby 2.0.</p>