簡體   English   中英

以不同的方式合並三個哈希的 arrays

[英]Merge three arrays of hashes in different way

我是 Ruby 的新手,正在嘗試構建會議應用程序。 我有三個包含哈希的 arrays :

  • 一個包含我預定的會議日期,因此是一組空的人
  • 一個包含每次會議邀請的人
  • 最后一個包含拒絕的人

這體現為:

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

我正在尋找一個可讀的解決方案,但我沒有找到任何人......

對不起我的英語,提前謝謝你,尼古拉斯

創建一個簡單的 hash

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

將 hash 轉換為哈希數組

h.map { |k,v| { :id=> k, :peoples=> v } }
  #=> [{:id=>"1", :peoples=>["Tom", "Nicolas"]},
  #    {:id=>"2", :peoples=>["Arthur", "Carl"]},
  #    {:id=>"3", :peoples=>[]}] 

我最初創建了一個 hash,只有在處理了受邀者和拒絕者之后,我才將其轉換為哈希數組。 這樣做可以加快:id查找添加和刪除人員的速度。 因此,如果n = meetings.size meeting.size ,這些計算的計算復雜度接近 O(n),“接近”,因為 hash 密鑰查找的計算復雜度接近 O(1)(即所需的時間定位一個鍵並且它的值幾乎是恆定的,不管散列的大小)。 相比之下,對於meetings的每個元素,在invited_peoplesabsent_peoples中搜索:id值的方法的計算復雜度為 O(n 2 )。

定義一個通過id查找object的方法

def find_by_id array_of_hash, id
  array_of_hash.find {|x| x[:id] == id} || {peoples: []}
end

使用 map 轉動一個新陣列,在 map 塊內只需使用您的邏輯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=>[]}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM