合并满足条件的哈希数组

时间:2018-02-02 17:25:13

标签: ruby

我有以下代码:

array = [{:date=>Sun, 10 Aug 2014, :slots=>[]},
 {:date=>Mon, 11 Aug 2014,
  :slots=>["9:30", "10:00", "10:30", "11:00", "11:30", "12:00"]},
 {:date=>Fri, 15 Aug 2014,
  :slots=>["9:30", "10:00", "10:30", "11:00", "11:30", "12:00"]},
 {:date=>Sat, 16 Aug 2014,
  :slots=>["9:30", "10:00", "10:30", "11:00", "11:30", "12:00"]},
 {:date=>Fri, 15 Aug 2014, :slots=>["14:30", "15:00"]}]

我想合并/添加:slot其中:date is equal

 final = [{:date=>Mon, 11 Aug 2014,
  :slots=>["9:30", "10:00", "10:30", "11:00", "11:30", "12:00"]},
 {:date=>Fri, 15 Aug 2014,
  :slots=>["9:30", "10:00", "10:30", "11:00", "11:30", "12:00", "14:30", "15:00" ]},
 {:date=>Sat, 16 Aug 2014,
  :slots=>["9:30", "10:00", "10:30", "11:00", "11:30", "12:00"]}]

2 个答案:

答案 0 :(得分:0)

final = array.each_with_object({}) do |hash, memo|
  memo[hash[:date]] ||= []
  memo[hash[:date]] |= hash[:slots]
end.each_with_object([]) do |(date, slots), memo|
  memo.push(date: date, slots: slots)
end

请注意,为了运行您的代码,我在日期对象周围添加了引号(尝试将Mon, 11 Aug 2014粘贴到IRB中,它会导致语法错误。)

无论如何,这是做什么的:

  1. 将哈希数组转换为单个哈希,其中键是日期,值是插槽数组。使用|=(“或等于”运算符)合并具有相同日期的插槽。
  2. 将哈希值恢复为原始格式(哈希数组)

答案 1 :(得分:0)

返回具有合并slot值的哈希数组的一种方法是生成一个新数组,遍历原始数据,比较日期值,并在适当时将插槽合并到新数组:

def merge_slots(array)
  result = []

  array.each do |hash|
    result_dates = result.map { |h| h[:date] }
    array_dates = array.map { |h| h[:date] }

    if matching_index = result_dates.find_index(hash[:date])
      matching_hash = array[matching_index]
      matching_hash[:slots] = matching_hash[:slots] | hash[:slots]
    else
      result << hash
    end
  end

  result
end

final = merge_slots(your_array)

希望这有帮助!