从ruby中的哈希数组中打印表到文件

时间:2013-04-16 07:03:03

标签: ruby arrays hash

我想把以下数组作为表格输出到file.txt。

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"}]

我想要的结果是:

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

如果我能更好地获得标题的Markdown: - )

许多TIA

1 个答案:

答案 0 :(得分: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