Ruby:合并数组或哈希 [英] Ruby: merging arrays or hashes

查看:45
本文介绍了Ruby:合并数组或哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解如何解决这个问题,本质上我有两个数组,如下所示:

I'm having trouble understanding how to solve this issue, essentially I have two arrays that look like:

第一个数组:

days_to_report
#=> [{:date=>Fri, 01 Apr 2011},
#=>  {:date=>Sat, 02 Apr 2011},
#=>  {:date=>Sun, 03 Apr 2011},
#=>  {:date=>Mon, 04 Apr 2011}]

第二个数组:

tracks_by_day
#=> [{:date=>Mon, 04 Apr 2011, :count=>905, :percentage=>13.205895228367137},
#=>  {:date=>Sat, 02 Apr 2011, :count=>6745, :percentage=>98.4240478622501},
#=>  {:date=>Fri, 01 Apr 2011, :count=>6853, :percentage=>100.0}]

在这种情况下,日期是 Date 对象.

所以我想合并它们,以便对于第一个数组 (days_to_report) 中的每个项目,都有第二个数组也有的数据,就像理想的输出一样:(注意Sun 日期的数据,2011 年 3 月 3 日)

So I want to like merge them so that for every item in the first array (days_to_report), has the data that the second array has too, like the ideal output would be: (notice the data for the date for Sun, 03 Apt 2011)

[{:date=>Mon, 04 Apr 2011, :count=>905,  :percentage=>13.205895228367137},
 {:date=>Sun, 03 Apr 2011, :count=>0,    :percentage=>0},
 {:date=>Sat, 02 Apr 2011, :count=>6745, :percentage=>98.4240478622501},
 {:date=>Fri, 01 Apr 2011, :count=>6853, :percentage=>100.0}]

请注意,数组的第二项的值为零,因为 :date 不在 tracks_by_day 数组的散列中......如何做到这一点?看起来像 zip 或其他东西中提供的功能,但我需要匹配键以查看它们是否存在,如果不存在则将它们的值填零.

Notice that the second item of the array has zero for the values because the :date wasn't in the hash for the tracks_by_day array... any thoughts on how to accomplish this? It seems like the functionality provided in zip or something, but I need to match up the keys to see if they exist and zero fill their values if they don't.

希望我的描述正确,再次感谢各位!高五!

I hope I'm describing this correctly, thanks again guys! high five!

推荐答案

days = days_to_report.map{|d| d[:date] } - tracks_by_day.map{|d| d[:date]}
days.each{ |d| tracks_by_day << {:date => d, :count => 0, :percentage => 0} }

days.inject(tracks_by_day){|a,d| a << {:date => d, :count => 0, :percentage => 0}}

这篇关于Ruby:合并数组或哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆