Ataraxy Ataraxy - 1 year ago 57
Ruby Question

How do I generate a table from an array of hashes without consistent keys?

I have an array of hashes that I want to turn into a table, but the tricky part is that the hash keys are not consistent:

a = [
"name" => "Jack",
"phone" => "9542221234",
"state" => "FL"
"name" => "John",
"job" => "Lawyer"
"name" => "Mike",
"campaign" => "test",
"state" => "NY"

I am at a loss for how to loop through the array, pull out the unique key name's and add the applicable values to rows. I'm trying to achieve this effect:

Name | Phone | State | Campaign | Job
Jack 9542221234 FL
John Lawyer
Mike NY test

I searched for a solution and looked into different gems such as Builder, but every example I found assumes that the key names are consistent and pulls the table header keys from the first hash within the array.

Answer Source
cols =
cols.each do |colname|
  printf "%-10s ", colname
a.each do |row|
  cols.each do |colname|
    printf "%-10s ", row[colname]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download