ruby - How to output a hash to a CSV line -


i'd map hash csv line.

i have couple of objects in hash:

person1 = {'first_name' => 'john', 'second_name' => 'doe', 'favorite_color' => 'blue', 'favorite_band' => 'backstreet boys'} person2 = {'first_name' => 'susan', 'favorite_color' => 'green', 'second_name' => 'smith'} 

i want transform csv file keys columns , values each row.

i can create headers creating csv::row this:

h = csv::row.new(all_keys_as_array,[],true) 

i cannot rely on order , more important, not values filled time.

but when try add rows table via << , array, mapping of headers ignored. has in right order.

to demonstrate this, wrote little script:

require 'csv'  person1 = {'first_name' => 'john', 'second_name' => 'doe', 'favorite_color' => 'blue', 'favorite_band' => 'backstreet boys'} person2 = {'first_name' => 'susan', 'favorite_color' => 'green', 'second_name' => '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 |p|   r = csv::row.new([],[],false)   p.each |k, v|     r << {k => v}   end   t << r end  puts t.to_csv 

i expect output:

first_name,last_name,favorite_color,favorite_band john,doe,blue,backstreet boys susan,smith,green, 

instead values in order appear. output this:

first_name,second_name,favorite_color,favorite_band john,doe,blue,backstreet boys susan,green,smith 

the strangest part is, when lookup via ['key'] correct values:

puts "favorite_bands: #{t['favorite_band']}" > favorite_bands: [nil, "backstreet boys", nil] 

so there way write csv file expect?

you can iterate on column names

persons.each |person|   r = csv::row.new([],[],false)   all_keys_as_array.each |key|     r << person[key]   end   t << r end 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -