以不同方式合并三个哈希数组

问题描述 投票:1回答:2

我是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=>[]}
]

我正在寻找一种可读的解决方案,但我找不到任何人...

对不起,我的英文,谢谢你,尼古拉斯

arrays ruby-on-rails ruby ruby-on-rails-3 hash
2个回答
1
投票

定义通过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=>[]}]


1
投票

创建简单的哈希

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查找以添加和删除人员。结果,如果n = meetings.size,则这些计算的计算复杂度接近O(n),“接近”,因为哈希键查找的计算复杂度接近O(1)(即,定位所需的时间)键,并且其值几乎是恒定的,而不管哈希的大小如何)。相反,对于:id的每个元素,在invited_peoplesabsent_peoples中搜索meetings的值的方法的计算复杂度为O(n 2)。

© www.soinside.com 2019 - 2024. All rights reserved.