我是Ruby的新手,正在尝试构建会议应用程序。我有三个包含哈希的数组:
此实现为:
meetings = [
{:id=>"1", :peoples=>[]}
{:id=>"2", :peoples=>[]}
{:id=>"3", :peoples=>[]}
]
invited_peoples = [
{:id=>"1", :peoples=>['Tom', 'Henry', 'Georges', 'Nicolas']}
{:id=>"2", :peoples=>['Arthur', 'Carl']}
]
absent_peoples = [
{:id=>"1", :peoples=>['Henry', 'Georges']}
]
而且我想参加:会议+被邀请的人-像这样的缺席的人
meetings_with_participants = [
{:id=>"1", :peoples=>['Tom', 'Nicolas']}
{:id=>"2", :peoples=>['Arthur', 'Carl']}
{:id=>"3", :peoples=>[]}
]
我正在寻找一种可读的解决方案,但我找不到任何人...
对不起,我的英文,谢谢你,尼古拉斯
创建简单的哈希
h = meetings.each_with_object({}) { |g,h| h[g[:id]] = g[:peoples] }
#=> {"1"=>[], "2"=>[], "3"=>[]}
添加受邀者
invited_peoples.each { |g| h[g[:id]] += g[:peoples] }
现在
h #=> {"1"=>["Tom", "Henry", "Georges", "Nicolas"],
# "2"=>["Arthur", "Carl"], "3"=>[]}
删除拒绝
absent_peoples.each { |g| h[g[:id]] -= g[:peoples] }
现在
h #=> {"1"=>["Tom", "Nicolas"], "2"=>["Arthur", "Carl"],
# "3"=>[]}
将哈希转换为哈希数组
h.map { |k,v| { :id=> k, :peoples=> v } }
#=> [{:id=>"1", :peoples=>["Tom", "Nicolas"]},
# {:id=>"2", :peoples=>["Arthur", "Carl"]},
# {:id=>"3", :peoples=>[]}]
我最初创建了一个哈希,只有在处理了被邀请者和拒绝者之后,我才将其转换为哈希数组。这样做可以加快:id
查找以添加和删除人员。
def find_by_id array_of_hash, id
array_of_hash.find {|x| x[:id] == id} || {peoples: []}
end
meetings + invited_peoples - absent_peoples like
result = meetings.map do |item|
id = item[:id]
{id: id, peoples: item[:peoples] + find_by_id(invited_peoples, id)[:peoples] - find_by_id(absent_peoples, id)[:peoples]}
end
=> [{:id=>"1", :peoples=>["Tom", "Nicolas"]}, {:id=>"2", :peoples=>["Arthur", "Carl"]}, {:id=>"3", :peoples=>[]}]