[英]Ruby On Rails sort the array of hash based on priority
請幫助我找到基於優先級排序的解決方案我沒有得到解決方案
優先級基於:
interview_proposal = [
{ interviewer_id: 3903, rating: 4, cronofy_enabled: false, slot_date: "2022-05-09" },
{ interviewer_id: 10, rating: 3.5, cronofy_enabled: false, slot_date: "2022-05-06" },
{ interviewer_id: 3902, rating: 2, cronofy_enabled: true, slot_date: "2022-05-06" },
{ interviewer_id: 3904, rating: 2.5, cronofy_enabled: false, slot_date: "2022-05-09" },
{ interviewer_id: 3905, rating: 3.5, cronofy_enabled: false, slot_date: "2022-05-09" }
]
# First priority picked earliest_slot
@earliest_slot = interview_proposal.find{|proposal| proposal[:slot_date] == "2022-05-06"}
#second priority rating
@max_rating = interview_proposal.max_by{|proposal| proposal[:rating]}
# Third priority cronofy_enabled
@calendar_synced = interview_proposal.find{|proposal| proposal[:cronofy_enabled]}
sorted_array = []
interview_proposal.each do |interview_proposal|
priority = match_count
sorted_array << { priority: priority, interview_proposal: interview_proposal }
end
sorted_array = sorted_array.
sort_by { |obj| obj[:priority] }.
reverse.map { |obj| obj[:interview_proposal] }
sorted_array
def match_count
count = 0
count += 1 if @earliest_slot[:slot_date].present?
count += 1 if @max_rating[:rating].present?
count += 1 if @calendar_synced[:cronofy_enabled]
count
end
在我看來,您可以通過使用Ruby 的排序方法來減少代碼的開銷。 如果 a > b,您需要在每個塊迭代中提供正數 integer,如果它們相等,則為 0;如果 b >a,則為負數 integer,以便排序工作。 starship 運算符 <=> 是前兩種情況的一個很好的快捷方式,但不適用於布爾值,因此我們在那里添加了額外的邏輯。
sorted_array = interview_proposal.sort do |a, b|
if (a[:slot_date] <=> b[:slot_date]) != 0
a[:slot_date] <=> b[:slot_date]
elsif (a[:rating] <=> b[:rating]) != 0
a[:rating] <=> b[:rating]
elsif a[:cronofy_enabled] == b[:cronofy_enabled]
0
elsif a[:cronofy_enabled]
1
else
-1
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.