print table to file from an array of hashes in rub

2019-06-08 12:12发布

问题:

I'd like to take the following array and output to a file.txt as a table.

arr=[{:food=>"", :calories=>"Calories", :carbs=>"Carbs", :fat=>"Fat", :protein=>"Protein", :cholest=>"Sodium"},
{:food=>"New York Bagel Co - Wholemeal Bagels*, 90 g bagel", :calories=>"223", :fat=>"2", :protein=>"9", :cholest=>"360"},
{:food=>"Nescafe - Decaf Coffee With Semi Skimmed Milk, 1 mug", :calories=>"12", :fat=>"0", :protein=>"1", :cholest=>"0"},
{:food=>"", :calories=>"235", :fat=>"2", :protein=>"10", :cholest=>"360"}]

The result I want is:

Food                                                Calories   Fat   Protein   Cholest
New York Bagel Co - Wholemeal Bagels*, 90 g bagel        223     2         9       360
Nescafe - Decaf Coffee With Semi Skimmed Milk, 1 mug      12     0         1         0
                                                         235     2        10       360

If I could get Markdown for the Titles even better :-)

Many TIA

回答1:

@col_width = arr.inject(Hash.new(0)) do |col_width, h|
  h.each{|k, v| col_width[k] = [col_width[k], v.length].max}
  col_width
end

arr.each do |h| puts h.map do |k, v|
  v.send(case k; when :food; :ljust else :rjust end, @col_width[k])
end.join("   ") end


标签: ruby arrays hash