title: How to output a hash to a CSV line
body: <p>I'd like to map a hash to a CSV line.</p>
  
  <p>I have a couple of objects in a hash:</p>
  
  <pre><code>person1 = {'first_name' =&gt; 'John', 'second_name' =&gt; 'Doe', 'favorite_color' =&gt; 'blue', 'favorite_band' =&gt; 'Backstreet Boys'}
  person2 = {'first_name' =&gt; 'Susan', 'favorite_color' =&gt; 'green', 'second_name' =&gt; 'Smith'}
  </code></pre>
  
  <p>I want to transform this into a CSV file with the keys as columns and the values for each row.</p>
  
  <p>I can easily create the headers by creating a <code>CSV::Row</code> like this:</p>
  
  <pre><code>h = CSV::Row.new(all_keys_as_array,[],true)
  </code></pre>
  
  <p>I cannot rely on the order and more important, not all values are filled all the time.</p>
  
  <p>But when I now try to add rows to the table via <a href="http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Row.html#method-i-3C-3C" rel="nofollow"><code>&lt;&lt;</code></a> and array, the mapping of the headers is ignored. It has to be in the right order.</p>
  
  <p>To demonstrate this, I wrote this little script:</p>
  
  <pre><code>require 'csv'
  
  person1 = {'first_name' =&gt; 'John', 'second_name' =&gt; 'Doe', 'favorite_color' =&gt; 'blue', 'favorite_band' =&gt; 'Backstreet Boys'}
  person2 = {'first_name' =&gt; 'Susan', 'favorite_color' =&gt; 'green', 'second_name' =&gt; 'Smith'}
  
  persons = [person1, person2]
  all_keys_as_array = %w{first_name second_name favorite_color favorite_band}
  
  h = CSV::Row.new(all_keys_as_array,[],true)
  t = CSV::Table.new([h])
  
  persons.each do |p|
    r = CSV::Row.new([],[],false)
    p.each do |k, v|
      r &lt;&lt; {k =&gt; v}
    end
    t &lt;&lt; r
  end
  
  puts t.to_csv
  </code></pre>
  
  <p>I would expect this output:</p>
  
  <pre><code>first_name,last_name,favorite_color,favorite_band
  John,Doe,blue,Backstreet Boys
  Susan,Smith,green,
  </code></pre>
  
  <p>Instead the values in the order as they appear. So the output is this:</p>
  
  <pre><code>first_name,second_name,favorite_color,favorite_band
  John,Doe,blue,Backstreet Boys
  Susan,green,Smith
  </code></pre>
  
  <p>The strangest part is, when I do a lookup via <a href="http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html#method-i-5B-5D" rel="nofollow"><code>['key']</code></a> I get the correct values:</p>
  
  <pre><code>puts "favorite_bands: #{t['favorite_band']}"
  &gt; favorite_bands: [nil, "Backstreet Boys", nil]
  </code></pre>
  
  <p>So is there any way to write to a CSV file as I expect?</p>