如何对对象数组

时间:2017-02-13 20:56:57

标签: arrays ruby hash

我在Ruby中有一个数据结构如下:

[["N1-Alb",
  {'Sun, 05 Feb 2017'=>"",
   'Mon, 06 Feb 2017'=>"",
   'Tue, 07 Feb 2017'=>"",
   'Wed, 08 Feb 2017'=>"0.25",
   'Thu, 09 Feb 2017'=>"0.03",
   'Fri, 10 Feb 2017'=>"",
   'Sat, 11 Feb 2017'=>""}],
 ["N1-Cet",
  {'Sun, 05 Feb 2017'=>"",
   'Mon, 06 Feb 2017'=>"7.8",
   'Tue, 07 Feb 2017'=>"",
   'Wed, 08 Feb 2017'=>"0.00",
   'Thu, 09 Feb 2017'=>"",
   'Fri, 10 Feb 2017'=>"",
   'Sat, 11 Feb 2017'=>""}],
 ["N3-Tju",
  {'Sun, 05 Feb 2017'=>"",
   'Mon, 06 Feb 2017'=>"",
   'Tue, 07 Feb 2017'=>"",
   'Wed, 08 Feb 2017'=>"3.15",
   'Thu, 09 Feb 2017'=>"",
   'Fri, 10 Feb 2017'=>"8.0",
   'Sat, 11 Feb 2017'=>""}],
 ["N7-Mlp",
  {'Sun, 05 Feb 2017'=>"",
   'Mon, 06 Feb 2017'=>"",
   'Tue, 07 Feb 2017'=>"5.01",
   'Wed, 08 Feb 2017'=>"0.03",
   'Thu, 09 Feb 2017'=>"",
   'Fri, 10 Feb 2017'=>"",
   'Sat, 11 Feb 2017'=>"4"}]]

如何以星期六,星期一等分别以哈希或数组格式获得所有星期日,星期一等的总和?

最终的哈希应该是:

result = { 'sun': '0', 
           'mon': '7.8', 
           'tue': '5.01', 
           'wed': '3.43', 
           'thu': '0.03', 
           'fri': '8.0', 
           'sat': '4' }

1 个答案:

答案 0 :(得分:1)

试试这个:

days = [:mon, :tue, :wed, :thu, :fri, :sat, :sun]

result = your_hash.each_with_object({}) do |n, h|
  n[1].each do |key, value|
    h[days[key.cwday - 1]] = (h[days[key.cwday - 1]].to_f + value.to_f).to_s
  end
end

根据您的要求,我将代码更新为更简洁。这段代码利用了nil.to_f == 0.0的事实,这可能会让一些人感到不安。