繁体   English   中英

Ruby On Rails 根据优先级对 hash 的数组进行排序

[英]Ruby On Rails sort the array of hash based on priority

请帮助我找到基于优先级排序的解决方案我没有得到解决方案

优先级基于:

  • 第一个选择最早的插槽
  • 第二个最大评级
  • 第三个 cronofy_enabled
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM