Ataraxy
Ataraxy

Reputation: 35

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.

Upvotes: 1

Views: 110

Answers (1)

zed_0xff
zed_0xff

Reputation: 33227

cols = a.map(&:keys).flatten.uniq
cols.each do |colname|
  printf "%-10s ", colname
end
puts
a.each do |row|
  cols.each do |colname|
    printf "%-10s ", row[colname]
  end
  puts
end

Upvotes: 2

Related Questions