Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>CSV supports "converters" for the <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html#method-i-header_convert" rel="nofollow">headers</a> and <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html#method-i-convert" rel="nofollow">fields</a>, which let you get inside the data before it's passed to your <code>each</code> loop. </p> <p>Writing a sample CSV file:</p> <pre><code>csv = "First,Last,Email ,Mobile Phone ,Company,Title ,Street,City,State,Zip,Country, Birthday,Gender ,Contact Type first,last,email ,mobile phone ,company,title ,street,city,state,zip,country, birthday,gender ,contact type " File.write('file_upload_example.csv', csv) </code></pre> <p>Here's how I'd do it:</p> <pre><code>require 'csv' csv = CSV.open('file_upload_example.csv', :headers =&gt; true) [:convert, :header_convert].each { |c| csv.send(c) { |f| f.strip } } csv.each do |row| puts "First Name: #{row['First']} \nLast Name: #{row['Last']} \nEmail: #{row['Email']}" end </code></pre> <p>Which outputs:</p> <pre><code>First Name: 'first' Last Name: 'last' Email: 'email' </code></pre> <p>The converters simply strip leading and trailing whitespace from each header and each field as they're read from the file.</p> <p>Also, as a programming design choice, don't read your file into memory using:</p> <pre><code>csv_text = File.read('file_upload_example.csv') </code></pre> <p>Then parse it:</p> <pre><code>csv = CSV.parse(csv_text, :headers =&gt; true) </code></pre> <p>Then loop over it:</p> <pre><code>csv.each do |row| </code></pre> <p>Ruby's IO system supports "enumerating" over a file, line by line. Once my code does <code>CSV.open</code> the file is readable and the <code>each</code> reads each line. The entire file doesn't need to be in memory at once, which isn't scalable (though on new machines it's becoming a lot more reasonable), and, if you test, you'll find that reading a file using <code>each</code> is extremely fast, probably equally fast as reading it, parsing it then iterating over the parsed file.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload