Reputation: 35
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
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